Search code examples
powershellfunctionparameters

Parameter set cannot be resolved


function f {
  param(
    [Parameter(ParameterSetName='A', Position=0)]
    [int] $Num,
    [Parameter(ParameterSetName='A', Position=1)]
    [Parameter(ParameterSetName='B', Position=0)]
    [scriptblock] $Script
  )
}

f 123 {}
f {}

Why can't the parameter set of the second call be resolved? It seems perfectly resolvable. At least there seems to be enough information for that.


Solution

  • You would need to add a DefaultParameterSetName to avoid ambiguity. On the second function call, PowerShell can't tell if you're wanting to use the parameter set A or B.

    function f {
        [CmdletBinding(DefaultParameterSetName = 'B')]
        param(
            [Parameter(ParameterSetName = 'A', Position = 0)]
            [int] $Num,
    
            [Parameter(ParameterSetName = 'A', Position = 1)]
            [Parameter(ParameterSetName = 'B', Position = 0)]
            [scriptblock] $Script
        )
    
        $PSCmdlet.ParameterSetName
    }
    
    f 123    # A
    f 123 {} # A
    f {}     # B