我正在尝试在运行外部命令时终止脚本导致错误。考虑一下这个简单的代码:
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.
答案 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