[英]How do I enforce command line argument checking in PowerShell
Here's my script (test.ps1): 这是我的脚本(test.ps1):
[CmdLetBinding()]
Param
(
[parameter(Mandatory=$true)][string]$environment,
[switch][bool]$continue=$true
)
Write-Host $environment
Write-Host $continue
Question: 题:
If I invoke this script by giving an argument which is a substring of the parameter I specified in the script like this: PS> .\\test.ps1 -envi:blah, PowerShell doesn't seem to check the argument name. 如果我通过提供一个参数来调用此脚本,该参数是我在脚本中指定的参数的子字符串,如下所示:PS>。\\ test.ps1 -envi:blah,PowerShell似乎不会检查参数名称。 I want PowerShell to enforce parameter spelling, ie, it should only accept -environment which matches the parameter name in the script.
我希望PowerShell强制执行参数拼写,即它只应接受与脚本中的参数名称匹配的-environment。 For anything else, it should raise an exception.
除此之外,它应该引发一个例外。 Is that doable?
那可行吗? How do I do that?
我怎么做?
Thanks. 谢谢。
It's not pretty, but it will keep you from using anything except -environment
as a parameter name. 它不是很漂亮,但是它将阻止您使用
-environment
作为参数名称。
Param
(
[parameter(Mandatory=$true)][string]$environment,
[parameter()]
[ValidateScript({throw "Invalid parameter. 'environment' required."})]
[string]$environmen,
[switch][bool]$continue=$true
)
Write-Host $environment
Write-Host $continue
}
Edit: As Matt noted in his comment the automatic disambiguation will force you to specify enough of the parameter name to find a unique substring match. 编辑:正如Matt在评论中指出的那样,自动消除歧义将迫使您指定足够的参数名称以查找唯一的子字符串匹配项。 What I'm doing here is basically giving it a parameter that satisfies all but the last character to prevent using any substring up to the last character (because it's ambiguous), and throwing an error to prevent you from using that.
我在这里所做的基本上是为它提供一个参数,该参数可以满足除最后一个字符以外的所有条件,以防止使用任何子字符串直到最后一个字符(因为其模棱两可),并抛出错误以阻止您使用它。
And, FWIW, that could well be the ugliest parameter validation I've ever done but I don't have any better ideas right now. 而且,FWIW,这很可能是我做过的最丑陋的参数验证,但是我现在没有更好的主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.