【问题标题】:PowerShell Try/Catch with If StatementsPowerShell Try/Catch 与 If 语句
【发布时间】:2018-01-27 11:51:07
【问题描述】:

问题/详情

我正在使用 PowerShell 并试图弄清楚自定义 Try Catch 语句是如何工作的。我当前的主要问题涉及混合 Try/Catch 和 If 语句。所以我想要实现的想法是这样的:

try {
    if (!$someVariable.Text) { throw new exception 0 }
    elseif ($someVariable.Text -lt 11) { throw new exception 1 }
    elseif (!($someVariable.Text -match '[a-zA-Z\s]')) { throw new exception 2}
}
catch 0 {
    [System.Windows.Forms.MessageBox]::Show("Custom Error Message 1")
}
catch 1 {
    [System.Windows.Forms.MessageBox]::Show("Custom Error Message 2")
}
catch 2 {
    [System.Windows.Forms.MessageBox]::Show("Custom Error Message 3")
}

现在我知道上面的代码在实际代码方面非常不准确,但我想直观地展示我的想法和尝试实现的目标。

问题

有谁知道如何使用 PowerShell 创建自定义错误消息,这可以帮助我实现接近上述想法的目标并稍微解释一下您的答案?提前谢谢你

到目前为止,下面的链接是我发现的最接近我想要实现的目标:

PowerShell Try, Catch, custom terminating error message

【问题讨论】:

    标签: powershell if-statement error-handling try-catch


    【解决方案1】:

    您抛出的错误存储在 $_.Exception.Message

    $a = 1
    try{
        If($a -eq 1){
            throw "1"
        }
    }catch{
        if ($_.Exception.Message -eq 1){
            "Error 1"
        }else{
            $_.Exception.Message
        }
    }
    

    【讨论】:

    • 啊!谢谢你。我现在明白了。所以我可以简单地使用throw 并在" " 中附加我想要的任何内容,然后当我执行我的catch 语句时......然后我可以使用if 或switch 解析那些。完美,完美。谢谢你。我不知道我怎么没听懂。
    【解决方案2】:

    我建议使用$PSCmdlet ThrowTerminatingError() 方法。这是一个例子:

    Function New-ErrorRecord
    {
        param(
            [String]$Exception,
            [String]$ExceptionMessage,
            [System.Management.Automation.ErrorCategory] $ErrorCategory,
            [String] $TargetObject
        )
    
        $e = New-Object $Exception $ExceptionMessage
        $errorRecord = New-Object System.Management.Automation.ErrorRecord $e, $ErrorID, $ErrorCategory, $TargetObject
        return $ErrorRecord
    }
    
    Try
    {
    If (not condition)
    {
        $Error = @{
          Exception = 'System.Management.Automation.ParameterBindingException'
          ExceptionMessage = 'Error text here'
          ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument
          TargetObject = ''
        }
        $PSCmdlet.ThrowTerminatingError((New-ErrorRecord @Error))
    }
    } Catch [System.Management.Automation.ParameterBindingException]
    {
        'do stuff'
    }
    

    【讨论】:

    • 我会将其归档以备后用。但就目前而言,@ArcSet 提供的简单答案已被证明非常有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    • 2016-11-25
    • 2010-09-24
    • 2021-12-25
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    相关资源
    最近更新 更多