给出:
function foo() {
Param(
[alias()]
$title
)
$null -eq $title
echo $title
}
然后同时用-title
和-t
调用它会导致错误:
PS> foo -title hi -t bar foo : Cannot bind parameter because parameter 'title' is specified more than once. To provide multiple values to parameters that can accept multiple values, use the array syntax. For example, "-parameter value1,value2,value3". At line:1 char:15 + foo -title hi -t bar + ~~ + CategoryInfo : InvalidArgument: (:) [foo], ParameterBindingException + FullyQualifiedErrorId : ParameterAlreadyBound,foo
如果我省略了别名指令,也会发生这种情况。我该如何解决这个问题,以便foo仅将-title
识别为$title
参数(而无需添加$t
参数)?
答案 0 :(得分:1)
如果(出于某种原因)您传递了不指定给该函数的参数, 这会干扰其他命名参数,您可以插入停止解析参数--%作为解决方法:
function foo() {
Param(
[alias()] $title,
[parameter(mandatory=$false, ValueFromRemainingArguments=$true)]$Remaining
)
"title: " + $title
"remaining:" + $Remaining
$PSBoundParameters
}
> foo -title bar --% -t (date)
title: bar
remaining:--% -t (date)
Key Value
--- -----
title bar
Remaining {--%, -t (date)}
> foo -title bar -- -t (date)
title: bar
remaining:-t 08/29/2019 16:17:57
Key Value
--- -----
title bar
Remaining {-t, 2019-08-29 16:17:57}