558

处理命令行参数的“最佳”方法是什么?

似乎有几个关于“最佳”方式的答案,因此我被困在如何处理简单的事情上:

script.ps1 /n name /d domain

script.ps1 /d domain /n name.

有没有插件可以更好地处理这个问题?我知道我在这里重新发明轮子。

显然,我已经拥有的并不漂亮,当然也不是“最好的”,但它确实有效……而且它很丑。

for ( $i = 0; $i -lt $args.count; $i++ ) {
    if ($args[ $i ] -eq "/n"){ $strName=$args[ $i+1 ]}
    if ($args[ $i ] -eq "-n"){ $strName=$args[ $i+1 ]}
    if ($args[ $i ] -eq "/d"){ $strDomain=$args[ $i+1 ]}
    if ($args[ $i ] -eq "-d"){ $strDomain=$args[ $i+1 ]}
}
Write-Host $strName
Write-Host $strDomain
4

1 回答 1

1044

你正在重新发明轮子。普通 PowerShell 脚本的参数以 开头-,例如script.ps1 -server http://devserver

然后param在文件开头的部分中处理它们。

您还可以为您的参数分配默认值,如果不可用则从控制台读取它们或停止脚本执行:

 param (
    [string]$server = "http://defaultserver",
    [Parameter(Mandatory=$true)][string]$username,
    [string]$password = $( Read-Host "Input password, please" )
 )

在脚本中,您可以简单地

write-output $server

因为所有参数都成为脚本范围内可用的变量。

在此示例中,$server如果在没有它的情况下调用脚本,则获取默认值,如果省略-username参数,脚本将停止,如果省略,则要求终端输入-password

更新:您可能还想将“标志”(布尔值 true/false 参数)传递给 PowerShell 脚本。例如,您的脚本可能会接受“强制”,当不使用强制时,脚本会以更谨慎的模式运行。

关键字是[switch]参数类型:

 param (
    [string]$server = "http://defaultserver",
    [string]$password = $( Read-Host "Input password, please" ),
    [switch]$force = $false
 )

在脚本中,您将像这样使用它:

if ($force) {
  //deletes a file or does something "bad"
}

现在,在调用脚本时,您可以像这样设置 switch/flag 参数:

.\yourscript.ps1 -server "http://otherserver" -force

如果您明确要声明未设置标志,则有一种特殊的语法

.\yourscript.ps1 -server "http://otherserver" -force:$false

相关 Microsoft 文档的链接(适用于 PowerShell 5.0;链接中也提供了 3.0 和 4.0 版本):

于 2010-01-28T20:13:40.883 回答