Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter binding issue in PowerShell

I have this PowerShell cmdlet:

function Test-ParameterBinding {
    #
    # .SYNOPSIS
    # Tests parameter binding.
    #
    [CmdletBinding()]
    param (    

        [Parameter(ParameterSetName = 's1', Mandatory = $true)]
        [int] $P1,

        [Parameter(ParameterSetName = 's1')]
        [Parameter(ParameterSetName = 's2', Mandatory = $true)]
        [string] $P2,

        [Parameter(ParameterSetName = 's1')]
        [Parameter(ParameterSetName = 's3', Mandatory = $true)]
        [bool] $P3
    )
    process { $PSCmdlet }
}

And here is the help for this cmdlet:

SYNTAX
    Test-ParameterBinding -P1 <Int32> [-P2 <String>] [-P3 <Boolean>] [<Com…

    Test-ParameterBinding -P2 <String> [<CommonParameters>]

    Test-ParameterBinding -P3 <Boolean> [<CommonParameters>]

Looking at the code and help I would think I could use the cmdlet like this:

Test-ParameterBinding -P2 'Bind to param set s2'
Test-ParameterBinding -P3 $true # Bind to param set s3

But for both of these I get:

Parameter set cannot be resolved using the specified named parameters.

Question 1: Should PowerShell be able to bind to parameter sets s2 and s3 in my two cases?

That means that there was not time to implement it for version 2 of PowerShell, or they did not uncover this issue.

Question 2: Is there something wrong with my reasoning here? Should parameter binding fail in these cases?


I found something that may be directly related to my issue here in the PowerShell documentation:

There is one case where Windows PowerShell cannot use the default parameter set even if a default parameter set name is specified. The Windows PowerShell runtime cannot distinguish between parameter sets based solely on object type. For example, if you have one parameter set that takes a takes a string as the file path, and another set that takes a FileInfo object directly, Windows PowerShell cannot determine which parameter set to use based on the values passed to the cmdlet, nor does it use the default parameter set. In this case, even if you specify a default parameter set name, Windows PowerShell throws an ambiguous parameter set error message.

like image 301
knut Avatar asked Oct 06 '22 14:10

knut


1 Answers

Your logic is correct, Powershell should be able to figure out the parameter set based on your function definition and example usages.

Apparently Powershell v2 simply did not have robust enough logic for this. It works as expected in Powershell v3, though, which is further confirmation that it's a shortcoming/bug in v2.

like image 97
latkin Avatar answered Oct 10 '22 03:10

latkin