为什么 Try/Catch 中的命令有时需要 -ErrorAction Stop,有时则不需要?

为什么 Try/Catch 中的命令有时需要 -ErrorAction Stop,有时则不需要?

在下面的例子中,我想用 来catch表示错误-ErrorAction Stop。在这种情况下,它工作得很好。

try
{
    Import-Module -ErrorAction Stop -Force nomodule.psm1
}
catch
{
    Write-Host -ForegroundColor Red "no module"

    $PSItem >> $env:HOMEPATH\AVSUB.log
    exit 1
}

但在下面的情况下,我没有使用-ErrorAction Stop并且该catch块仍然运行。

try
{
    $var= broken_function
}
catch
{
   Write-Host -ForegroundColor Red "error"

   $PSItem >> $env:HOMEPATH\AVSUB.log
   exit 1
}

为什么有时候需要指定-ErrorAction Stop,有时候不需要?

答案1

终止非终止PowerShell 中的错误。

终止错误是停止 cmdlet、脚本或程序执行的错误。 无需 即可捕获此Try {} Catch {}错误-ErrorAction Stop

非终止错误允许 PowerShell 继续执行。您可以通过添加 来捕获它们-ErrorAction Stop

这里有两个函数,一个产生终止错误,另一个产生非终止错误。

# This will throw a terminating error
function TerminatingErrorExample {
    [CmdletBinding()]
    Param()
    Throw "I can't run like this!"
    Write-Host "This message will never be displayed, because it's after the terminating error."
}

# This will write a non-terminating error
function NonTerminatingErrorExample {
    [CmdletBinding()]
    Param($i = 5)
    if ($i -gt 4) {
        Write-Error "I expected a value less or equal to 4!"
    }
    Write-Host "However, I can still continue the execution"
}

如果你好奇我为什么[CmdletBinding()]在函数中使用,那是因为如果没有它,函数就不支持[<CommonParameters>],并且-ErrorAction Stop是一个公共参数。

现在我们可以把它们包装起来Try {} Catch {}

# Because the function produces a terminating error, the Catch block will run
Try {
    TerminatingErrorExample
} Catch {
    Write-Host "I got you!"
}

# Since the error here is non-terminating, the catch block won't run
Try {
    NonTerminatingErrorExample
} Catch {
    Write-Host "You won't see this message"
}

# Now the catch block will run, because we specifically say we want it to stop,
# even on a non-terminating error.
Try {
    NonTerminatingErrorExample -ErrorAction Stop
} Catch {
    Write-Host "Now you see this message."
}

如果我们运行这个,返回的结果将和预期的一样:

I got you!
NonTerminatingErrorExample : I expected a value less or equal to 4!
In Zeile:28 Zeichen:5
+     NonTerminatingErrorExample
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,NonTerminatingErrorExample

However, I can still continue the execution
Now you see this message.

相关内容