从外部Windows命令实用程序捕获异常

时间:2018-03-26 16:42:41

标签: powershell exception-handling

我正在尝试在运行外部命令时终止脚本导致错误。考虑一下这个简单的代码:

try {
    where.exe Test-App
}

catch {
    Write-Error "Exception caught." -ErrorAction Continue
    throw
}

Write-Host "Test message!"

输出:

where.exe : INFO: Could not find files for the given pattern(s).
At line:2 char:5
    where.exe Test-App
...
Test message!

当外部命令导致错误时,是否可以进入catch块并抛出?

期望的输出:

C:\Scripts\Test-Script.ps1 : Exception caught.

1 个答案:

答案 0 :(得分:1)

作为TheIncorrigible1 suggests,请检查$LASTEXITCODE,如下所示:

$where = where.exe test 2>&1
if($LASTEXITCODE -ne 0){
    throw "Exception caught."
    return
}
# otherwise continue, grab actual output from $where