【问题标题】:Powershell: How to catch an Error correctly? ErrorAction -Stop vs. exitPowershell:如何正确捕获错误? ErrorAction - 停止与退出
【发布时间】:2020-11-03 11:48:21
【问题描述】:

当我想在遇到错误时停止 Powershell 脚本,我应该如何停止脚本?

-ErrorAction -Stop ..

try {
     foo.bar
catch{
    $ErrorMsg = "An error occured during foo.bar"
    Write-Error -Message $ErrorMsg -ErrorAction Stop
}

try {
     foo.bar
catch{
    $ErrorMsg = "An error occured during foo.bar"
    Write-Error -Message $ErrorMsg
    exit
}

什么是最佳实践和推荐?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您可以预先将$ErrorActionPreference 设置为停止,然后在try{} 中调用您的脚本。如果脚本遇到应终止脚本的错误,则应使用throw,以便它冒泡到调用脚本。

    类似

    $oldErrorAction = $ErrorActionPreference
    $ErrorActionPreference = 'Stop'
    try {
         foo.bar
    }
    catch{
        # re-throw the exception
        throw
    }
    finally {
        # reset the ErrorActionPreference
        $ErrorActionPreference = $oldErrorAction
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      相关资源
      最近更新 更多