从外部Windows命令实用程序捕获异常 [英] Catch exception from external windows command utility
本文介绍了从外部Windows命令实用程序捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在运行外部命令导致错误时终止脚本。考虑以下简单代码:
try {
where.exe测试应用程序
}
catch {
写错误捕获到异常。 -ErrorAction继续
抛出
}
写入主机测试消息!
输出:
where.exe:信息:找不到给定模式的文件。
在第2行:char:5
where.exe测试应用程序
...
测试消息!
当外部命令导致错误时,是否可以进入catch块并抛出? / p>
所需的输出:
C:\Scripts\Test- Script.ps1:捕获到异常。
解决方案
为 TheIncorrigible1建议,检查 $ LASTEXITCODE
,像这样:
$ where = where.exe test 2>& 1
if($ LASTEXITCODE -ne 0 ){
抛出捕获到异常。
return
}
#否则继续,从$ where获取实际输出,其中
I'm trying to terminate a script when running an external command results in an error. Consider this simple code:
try {
where.exe Test-App
}
catch {
Write-Error "Exception caught." -ErrorAction Continue
throw
}
Write-Host "Test message!"
Output:
where.exe : INFO: Could not find files for the given pattern(s).
At line:2 char:5
where.exe Test-App
...
Test message!
Is it possible to enter the catch block and throw, when an external command results in an error?
Desired output:
C:\Scripts\Test-Script.ps1 : Exception caught.
解决方案
As TheIncorrigible1 suggests, inspect $LASTEXITCODE
, like so:
$where = where.exe test 2>&1
if($LASTEXITCODE -ne 0){
throw "Exception caught."
return
}
# otherwise continue, grab actual output from $where
这篇关于从外部Windows命令实用程序捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文