这"规则"在PowerShell文档中说明,例如here。 但是,我不确定我是否正确地解释了它。以下似乎对我很好。
function Test-ParameterSets
{
param(
[Parameter(Position = 0, ParameterSetName = "NameName")]
[Parameter(Position = 0, ParameterSetName = "NameId")]
[string] $A_by_Name,
[Parameter(Position = 0, ParameterSetName = "IdName")]
[Parameter(Position = 0, ParameterSetName = "IdId")]
[int] $A_by_Id,
[Parameter(Position = 1, ParameterSetName = "NameName")]
[Parameter(Position = 1, ParameterSetName = "IdName")]
[string] $B_by_Name,
[Parameter(Position = 1, ParameterSetName = "NameId")]
[Parameter(Position = 1, ParameterSetName = "IdId")]
[int] $B_by_Id
)
write-host "Hello"
}
我误解了吗?或者规则是否过时了?
答案 0 :(得分:0)
你还没有充分展示自己的榜样:
function Test-ParameterSets
{
param(
[Parameter(Position = 0, ParameterSetName = "NameName")]
[Parameter(Position = 0, ParameterSetName = "NameId")]
[string] $A_by_Name,
[Parameter(Position = 0, ParameterSetName = "IdName")]
[Parameter(Position = 0, ParameterSetName = "IdId")]
[int] $A_by_Id,
[Parameter(Position = 1, ParameterSetName = "NameName")]
[Parameter(Position = 1, ParameterSetName = "IdName")]
[string] $B_by_Name,
[Parameter(Position = 1, ParameterSetName = "NameId")]
[Parameter(Position = 1, ParameterSetName = "IdId")]
[int] $B_by_Id
)
"ParametetSetName is $($PSCmdlet.ParameterSetName)"
}
输出:
Test-ParameterSets : Parameter set cannot be resolved using the specified named parameters.
At line:25 char:1
+ Test-ParameterSets
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Test-ParameterSets], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Test-ParameterSets
当您有不同的行为或使用不同的参数时,通常使用ParamaterSetName,具体取决于您的函数用户使用的参数集。规则是正确的。您可以使用DefaultParameterSetName
属性的CmdletBinding
属性帮助PowerShell确定正在使用的参数。