IttayD
IttayD

Reputation: 29143

How to disable short parameter names

Given:

function foo() {
    Param(
        [alias()]
        $title
    )
    $null -eq $title
    echo $title
}

Then calling it with both -title and -t results in an error:

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

This happens also if I omit the alias directive. How can I fix this so that foo only recognizes -title as the $title parameter (withoug adding a $t parameter)?

Upvotes: 2

Views: 657

Answers (1)

user6811411
user6811411

Reputation:

If (for whatever reason) you pass parameters not destined to the function, which interfere with other named parameters you might insert the stop parsing parameter --% as a workaround:

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

EDIT an alternative, due to AnsgarWiechers good hint:

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

Upvotes: 3

Related Questions