如何禁用简短的参数名称

时间:2019-08-29 07:48:31

标签: powershell parameters

给出:

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参数)?

1 个答案:

答案 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)}

由于AnsgarWiechers很好的提示,请编辑替代项:

> 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}