您可以使用参数属性来声明多个参数集。然后,您只需将互斥的参数分配给不同的参数集。
编辑:
这也记录在“参数集名称命名参数”部分的“about_Functions_Advanced_Parameters”中。这是使用 cmdlet 处理不同参数集的方式,例如Get-Random
(具有互斥参数):
> get-random -input 4 -max 77
Get-Random : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:11
+ get-random <<<< -input 4 -max 77
+ CategoryInfo : InvalidArgument: (:) [Get-Random], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.GetRandomCommand
这是在函数中执行此操作的示例:
function exclusive_params() {
param(
[parameter(ParameterSetName="seta")]$one,
[parameter(ParameterSetName="setb")]$two,
$three
)
"one: $one"; "two: $two"; "three: $three"
}
参数one
和two
位于不同的参数集中,因此不能一起指定:
> exclusive_params -one foo -two bar -three third
exclusive_params : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:17
+ exclusive_params <<<< -one foo -two bar -three third
+ CategoryInfo : InvalidArgument: (:) [exclusive_params], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,exclusive_params
这与我使用 Get-Random 时遇到的错误相同。但我可以独立使用参数:
> exclusive_params -one foo -three third
one: foo
two:
three: third
...或者:
> exclusive_params -two bar -three third
one:
two: bar
three: third