I am trying to call a PowerShell function that has a parameter set, using another PowerShell function with a parameter set. In the code below, I want to call Entry-Point using either the -ABC or -DEF switch, not both. However, when I run Entry-Point with any number of parameters, I get the AmbiguousParameterSet exception below.
function My-Function {
[CmdletBinding(DefaultParameterSetName='ABC')]
Param(
[Parameter(Mandatory=$false, ParameterSetName='ABC', Position=1)]
[switch] $ABC,
[Parameter(Mandatory=$false, ParameterSetName='DEF', Position=1)]
[switch] $DEF,
[switch] $Extra
)
echo $ABC
echo $DEF
echo $Extra
}
function Entry-Point {
[CmdletBinding(DefaultParameterSetName='ABC')]
Param(
[Parameter(Mandatory=$false, ParameterSetName='ABC', Position=1)]
[switch] $ABC,
[Parameter(Mandatory=$false, ParameterSetName='DEF', Position=1)]
[switch] $DEF,
[switch] $Extra
)
My-Function -ABC:$ABC -DEF:$DEF -Extra:$Extra
}
My-Function : Parameter set cannot be resolved using the specified named
parameters.
At line:24 char:1
+ My-Function -ABC:$ABC -DEF:$DEF -Extra:$Extra
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [My-Function], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,My-Function
How can I pass the parameters -ABC and -DEF -- whether each was specified or not -- from function Entry-Point to function My-Function?
The quick answer is splatting. PowerShell lets you present a hashtable as the parameters to a function (using @ instead of $), and uses the keys of the hashtable as parameter names, the values are the parameter values.
Also, each advanced function automatically sets $PSBoundParameters as a hashtable of the parameters that are passed in.
So...you can just say:
My-Function @PSBoundParameters