使用以下示例函数:
Function Test {
param(
[Parameter(Position=0)]
[string]$Optional="some optional string",
[Parameter(Position=1, Mandatory=$true)]
[string]$Required
)
Process { }
}
我希望以下内容是相同的:
Test -Optional "optional" "required"
和
Test "required"
不是,但是为什么呢?可选参数不是必需的,但是第二个示例将失败:
无法使用指定的命名参数来解析参数集。发出的一个或多个参数不能一起使用,或者提供的参数数量不足。
很自然,如果仅指定一个参数,则它将成为必需参数,因为需要指定它。
有什么办法可以完成我想做的事情?
When you give a parameter a position before a required one, it's not required, but it will be expected that the first input will be your optional parameter. To make your second example work, you just need to remove the Position reference for the non-required parameter. Of course then
Required
would be the first position parameter or0
.I added some output and remove the default value for the
Optional
parameter so you can see what happens.如果不想命名可选参数,则将其位置设置为高于所需参数的位置。
About Functions Advanced Parameters