PowerShell:使用参数验证而不会引发异常 [英] PowerShell : use parameter validation without throwing exception
问题描述
我想通过以下方式调用PowerShell脚本:
script.ps1 -path mypath\to\files\ -days 6 -hours 0
要验证命令行参数,我可以手动操作,也可以依靠 param
语法:
Param(
[Parameter(Mandatory = $ true)] [string] $ path,
[Parameter(Mandatory = $ false)] [int] $ days,
[Parameter(Mandatory = $ false)] [int] $ hours
)
如果我使用 param
语法:
-
参数定义必须是脚本的第一行(不包括注释)。好的,对我来说不是问题
-
如果参数不正确,我将无法捕获错误(例如显示自定义错误消息)> p>
我想显示一个自定义错误的参数调用脚本时出现错误消息。
在参数错误的情况下是否有可能以及如何捕获异常?
好的,不可能使用 param
AND来捕获相关的异常。
I'd like to call a PowerShell script this way :
script.ps1 -path mypath\to\files\ -days 6 -hours 0
To validate the command line arguments, I can either do it by hand, either rely on the param
syntax :
Param (
[Parameter(Mandatory=$true )] [string] $path,
[Parameter(Mandatory=$false)] [int] $days,
[Parameter(Mandatory=$false)] [int] $hours
)
If I use the param
syntax :
the param definition must be the first line in the script (excluding comments). Okay, not a problem for me
in case of incorrect parameters, I can't catch the error (for example to display a custom error message)
I'd like to display a custom error message when the script is called with wrong parameters.
Is it possible, and how, to catch the exception in case of parameter error ?
So okay, it is not possible to use param
AND to catch the related exceptions.
这篇关于PowerShell:使用参数验证而不会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!