开发者

How to specify a non-positional parameter in a PowerShell script?

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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜