如何在 PowerShell 脚本中指定非位置参数? [英] How to specify a non-positional parameter in a PowerShell script?
问题描述
我在脚本的开头有以下 param
块
I've got the following param
block at the start of a script
param(
[string]$command,
[string]$version = "1.1.0"
)
这很好,只是我需要$version
不是一个位置参数,这样如果你输入
This is fine, only I need $version
to not be a positional parameter, so that if you type
.\script.ps1 run argument
然后 $args
应该包含argument",$version
应该是1.1.0".我知道我可以使用 C# Cmdlet 来完成它,但如果我可以将它作为单个脚本交付会更方便.
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.
推荐答案
在 PowerShell 1.0 中,AFAIK 不可能.如果您不希望它是位置参数,则需要删除 $version 参数.
In PowerShell 1.0, not possible AFAIK. You would need to remove the $version parameter if you don't want it to be positional.
在 PowerShell 2.0 中,您可以通过创建一个高级函数来获得您想要的东西,您可以在其中指定参数属性中的附加信息,例如:
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
这篇关于如何在 PowerShell 脚本中指定非位置参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!