I seem often to find myself in a situation where I have a bunch of variables set up and I want to pass them in to a function (for example, passing parameters to another function without modification). Currently I end up doing something like this:
Get-RelatedThing -CompanyTag $CompanyTag -ProjectTag $ProjectTag -EnvName $EnvName
This seems verbose and not hugely readable. I could use positional parameters, but that sacrifices clarity and compatibility. Precreating an array and splatting just creates vertical clutter rather than horizontal (except in the unusual case where I can do something like Get-RelatedThing @PSBoundParameters, but this has pitfalls).
What I'd really like is to be able to do something like:
Get-RelatedThing @(Get-Variable CompanyTag,ProjectTag,EnvName)
but Get-Variable returns an Object[] and the splatting operator can only parse a hashtable of named params (or an array of positional params). I stole a function to solve this problem:
function Get-VariablesAsHashtable {
[CmdletBinding()]
param
(
[Parameter(Position=0)]
[string[]] $Name
)
$ObjectArray = Get-Variable -Name @($Name)
$Hashtable = @{}
$ObjectArray | Foreach { $Hashtable[$_.Name] = $_.Value }
return $Hashtable
}
which works when run "in advance":
# works
$calculatedVars = (Get-VariablesAsHashtable ProjectTag,EnvName,ComponentTag);
(Get-RelatedThing @calculatedVars);
but NOT when run "inline":
# fails
(Get-RelatedThing @(Get-VariablesAsHashtable ProjectTag,EnvName,ComponentTag));
Get-InitialThing : Cannot process argument transformation on parameter 'ProjectTag'. Cannot convert value to type System.String.
Am I missing something that would fix this approach? Or is there a better way of doing this?