10

I want parameters ONLY through alias:

script.ps1 -d site1 -c eac34b2d

This shouldnt be allowed:

script.ps1 site1 eac34b2d

Param(
    [parameter(Mandatory=$true)]
    [alias("d")]
    $DocRoot,
    [alias("c")]
    $Commit
)

2 Answers 2

7

Basically you want to disable positional parameter binding. I wrote about a built-in way in Powershell 3.0: use [CmdletBinding(PositionalBinding=$false)].

http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2011/09/19/how-to-disable-positional-parameter-binding-in-powershell.aspx

A workaround for v2 is available here:

http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/abbc587f-cd7e-4c8d-879f-355339d9d6b7/

Sign up to request clarification or add additional context in comments.

3 Comments

awsome. exactly what i needed.
Please embed your solutions, and no provide a link. For Your Information, your links do not work anymore.
the links dont work :(
0

Specify [CmdletBinding(PositionalBinding=$false)] before the param() block.
(This should work for functions as well as script params.)


The docs for Powershell 7.5 state:

In functions that have the CmdletBinding attribute, unknown parameters and positional arguments that have no matching positional parameters cause parameter binding to fail.

When PositionalBinding is $false, function parameters are not positional by default. Unless the Position argument of the Parameter attribute is declared on the parameter, the parameter name (or an alias or abbreviation) must be included when the parameter is used in a function.

The Position argument of the Parameter attribute takes precedence over the PositionalBinding default value. You can use the Position argument to specify a position value for a parameter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.