8

I've got the following param block at the start of a script

param(
 [string]$command,
 [string]$version = "1.1.0"
)

This is fine, only I need $version to not be a positional parameter, so that if you type

.\script.ps1 run argument

Then $args should contain "argument" and $version should be "1.1.0". I know I can do it with a C# Cmdlet, but it would be more convenient if I could deliver this as a single script.

1 Answer 1

6

In PowerShell 1.0, not possible AFAIK. You would need to remove the $version parameter if you don't want it to be positional.

In PowerShell 2.0, you can get what you want by creating an advanced function in which you specify additional info in a Parameter attribute e.g.:

function foo {    
    param(
        [Parameter(Mandatory=$true, Position = 0)]
        [string]
        $command,

        [Parameter()]
        [string]
        $version = "1.1.0",

        [Parameter(ValueFromRemainingArguments = $true)]
        $remainingArgs
    )

    Process {
        $OFS = ','
        "command is $command"
        "version is $version"
        "remainingArgs are $remainingArgs"
    }
}

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

4 Comments

If you remove the "Position = 0" from the first param, all of the remaning params seem to revert to positional params. Any idea how one could create a set of params for which all of them are optional?
If you don't set Mandatory=$true (or just remove the [Parameter()] altogether) then a parameter is considered optional.
I don't seem to be able to create a param list with no positional params, I'm afraid. I'll open up a detailed question about this in a moment.
I've opened a question for my particular corner-case version of this problem here: http://stackoverflow.com/questions/12375919/powershell-non-positional-optional-params

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.