问题描述
底线向上
我正在寻找一种方法来验证powershell(v1)命令行参数,而又不会将异常传播回命令行.
I'm looking for a method to validate powershell (v1) command line parameters without propagating exceptions back to the command line.
详细信息
我有一个Powershell脚本,当前将param
与[ValidateNotNullOrEmpty]
结合使用以验证命令行参数:
I have a powershell script that currently uses param
in conjunction with [ValidateNotNullOrEmpty]
to validate command line paramaters:
param(
[string]
[ValidateNotNullOrEmpty()]$domain = $(throw "Domain (-d) param required.")
)
我们正在更改错误处理的范式,不再需要将异常传递回命令行,而是提供自定义错误消息.由于param
块不能包装在try catch块中,因此我采取了 like 这样的方法:
We're changing the paradigm of error handling where we no longer want to pass exceptions back to the command line, but rather provide custom error messages. Since the param
block can not be wrapped in a try catch block, i've resorted to something like the following:
param(
[string]$domain = $("")
)
Try{
if($domain -like $("")){
throw "Domain (-d) param required."
}
...
}Catch{
#output error message
}
我担心的是,我们将绕过使用param
可用的所有内置验证.我的新技术是合理的解决方案吗?在将异常封装到脚本中时,是否有更好的方法来验证命令行参数?我对查看PowerShell专业人员如何处理这种情况非常感兴趣.
My concern is that we're bypassing all of the built-in validation that is available with using param
. Is my new technique a reasonable solution? Is there a better way to validate command line params while encapsulating exceptions within the script? I'm very much interested in see how PowerShell professionals would handle this situation.
任何建议将不胜感激.
Any advice would be appreciated.
推荐答案
正如我在评论中所提到的:更多地阅读您的描述,更多地得出结论,您不必担心绕过所有内置验证" .为什么?因为那完全是您的目标.您想绕过它的默认行为,因此,如果这是您需要且必须做的-那就别做. ;)
As I mentioned in a comment: more I read your description, more I come to the conclusion that you should not worry about "bypassing all built-in validation". Why? Because that's exactly your target. You want to bypass it's default behavior, so if that's what you need and have to do - than just do it. ;)
这篇关于在PowerShell中引发参数异常的替代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!