Reputation: 1537
This following error occurs when a variable, e.g. varSuffixed
, passed as an argument to a function is prefixed with the other variable name, e.g. var
, which also passed to the function but is not specified as an argument within the function: Cannot bind parameter because parameter 'varSuffixed' is specified more than once.
The error does not occur if both arguments are specified or if the prefix variable is the specified argument in the function. The error also occurs when not splatting the variables as well.
An example is below:
$args = @{
"var"="blah";
"varSuffixed"="blah2";
}
function Do-WorkingFunction($var, $varSuffixed){
Write-Host($var)
Write-Host($varSuffixed);
}
function Do-BrokenFunction($varSuffixed){
Write-Host($varSuffixed);
}
Do-WorkingFunction @args
Do-BrokenFunction @args
When trying to access the variable varSuffixed
in Do-BrokenFunction
, the following error occurs: Cannot bind parameter because parameter 'varSuffixed' is specified more than once.
Can anybody explain why this is?
This has been tested with PowerShell versions 2 and 5.
Upvotes: 0
Views: 192
Reputation: 28759
The problem is that matching parameter names in PowerShell happens by partial naming, as long as the name is unique. You'll notice that Do-BrokenFunction -var 3
works, even though Do-BrokenFunction
has no parameter named var
. Conversely, Do-BrokenFunction -var 3 -varSuffixed 4
fails, and that's exactly what you're doing when splatting.
There's not really any workaround for this other than to not do it. Either make sure your functions eat parameters that are all uniquely distinguishable, or pass only relevant parameters as arguments (recommended), or have your function accept a hash table directly and pluck the values from there. You could, I suppose, write a rather complicated metafunction that filters the hashtable based on what a function actually expects, but that seems to me far more trouble than it's worth.
Upvotes: 1