你正在重新发明轮子。普通 PowerShell 脚本的参数以-
, like script.ps1 -server http://devserver
然后你在一个param
部分(请注意,这must从脚本中的第一个非注释行开始)。
您还可以为参数分配默认值,如果不可用则从控制台读取它们或停止脚本执行:
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"
}
现在,在调用脚本时,您可以像这样设置开关/标志参数:
.\yourscript.ps1 -server "http://otherserver" -force
如果您明确想要声明未设置该标志,则有一个特殊的语法
.\yourscript.ps1 -server "http://otherserver" -force:$false
相关 Microsoft 文档的链接(适用于 PowerShell 5.0;3.0 和 4.0 版本也可在链接中找到):
- about_Scripts https://technet.microsoft.com/en-us/library/hh847841.aspx
- about_函数 https://technet.microsoft.com/en-us/library/hh847829.aspx
- about_Functions_Advanced_Parameters https://technet.microsoft.com/en-us/library/hh847743.aspx