【问题标题】:PowerShell catch exception in Param() blockPowerShell 在 Param() 块中捕获异常
【发布时间】:2019-09-27 11:49:40
【问题描述】:
Param(
    [ValidateRange(21,90)]
    [int[]]$Age
)

$age 超出范围时如何捕获异常?

【问题讨论】:

  • 参数验证的异常必须被调用者捕获。它不能被Param() 块捕获。这会破坏参数验证的目的。
  • 如果我无法捕获异常,那么 [ValidateRange] 的主要目的是什么?
  • 保存exceptional situations 的例外情况。一般预计用户会提供不合适的参数值。[citation needed]
  • 目的是确保脚本或函数仅在参数接收到有效值时运行,否则不运行。如果您希望参数接受任何内容并处理您自己获得的任何值:不要使用参数验证。在函数/脚本主体中进行自己的类型检查(例如在 Begin {} 块中)。
  • 此外,我并没有说你不能捕捉到异常。我说你不能在Param() 块中抓住它。

标签: powershell powershell-3.0


【解决方案1】:

正如在 cmets 中所指出的,需要在调用上下文中捕获验证错误

try{
  .\Set-Age.ps1
}
catch [System.Management.Automation.ParameterBindingException] {
  Write-Host "Error thrown while attempting to bind an argument to parameter $($_.Exception.ParameterName), with message: $($_.Exeption.Message)"
}
catch {
  # something other than the parameter binder threw an exception
}

【讨论】:

    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 2013-09-01
    • 1970-01-01
    相关资源
    最近更新 更多