PowerShell中的参数绑定问题

knu*_*nut 5 powershell parameterbinding

我有这个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 }
}
Run Code Online (Sandbox Code Playgroud)

以下是此cmdlet的帮助:

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

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

    Test-ParameterBinding -P3 <Boolean> [<CommonParameters>]
Run Code Online (Sandbox Code Playgroud)

查看代码和帮助我认为我可以像这样使用cmdlet:

Test-ParameterBinding -P2 'Bind to param set s2'
Test-ParameterBinding -P3 $true # Bind to param set s3
Run Code Online (Sandbox Code Playgroud)

但对于这两个我得到:

Parameter set cannot be resolved using the specified named parameters.
Run Code Online (Sandbox Code Playgroud)

问题1:如果PowerShell中能够绑定到参数集s2,并s3在我的两个案件?

这意味着没有时间为PowerShell的第2版实现它,或者他们没有发现这个问题.

问题2:我的推理在这里有什么问题吗?参数绑定在这些情况下是否会失败?


我在PowerShell文档中找到了可能与我的问题直接相关的内容:

有一种情况是,即使指定了默认参数集名称,Windows PowerShell也无法使用默认参数集.Windows PowerShell运行时无法仅基于对象类型区分参数集.例如,如果您有一个参数集,其中取一个字符串作为文件路径,另一个集合直接接受FileInfo对象,则Windows PowerShell无法根据传递给cmdlet的值确定要使用的参数集,也不能它使用默认参数集.在这种情况下,即使您指定了默认参数集名称,Windows PowerShell也会抛出不明确的参数集错误消息.

lat*_*kin 4

你的逻辑是正确的,Powershell应该能够根据你的函数定义和示例用法找出参数集。

显然 Powershell v2 根本没有足够强大的逻辑来实现这一点。不过,它在 Powershell v3 中按预期工作,这进一步证实了它是 v2 中的缺点/错误。