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

Catch exception from external windows command utility

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

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.

作为,检查$LASTEXITCODE,像这样:

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