尝试在 Powershell 中捕获可执行的 exe? [英] Try Catch on executable exe in Powershell?
问题描述
我想在 Powershell 中对 .exe 执行 Try Catch,我的内容如下所示:
I want to do a Try Catch on an .exe in Powershell, what I have looks like this:
Try
{
$output = C:\psftp.exe ftp.blah.com 2>&1
}
Catch
{
echo "ERROR: "
echo $output
return
}
echo "DONE: "
echo $output
当我说一个无效域时,它返回一个错误,如 psftp.exe : Fatal: Network error: Connection denied
但我的代码没有捕捉到.
When I use say an invalid domain, it returns an error like psftp.exe : Fatal: Network error: Connection refused
but my code is not catching that.
我如何捕捉错误?
推荐答案
try/catch
在 PowerShell 中不适用于本机可执行文件.调用 psftp.exe 后,检查自动变量 $LastExitCode
.这将包含 psftp 的退出代码,例如:
try / catch
in PowerShell doesn't work with native executables. After you make the call to psftp.exe, check the automatic variable $LastExitCode
. That will contain psftp's exit code e.g.:
$output = C:\psftp.exe ftp.blah.com 2>&1
if ($LastExitCode -ne 0)
{
echo "ERROR: "
echo $output
return
}
上面的脚本假定 exe 在成功时返回 0,否则返回非零.如果不是这种情况,请相应地调整 if (...)
条件.
The script above presumes that the exe returns 0 on success and non-zero otherwise. If that is not the case, adjust the if (...)
condition accordingly.
这篇关于尝试在 Powershell 中捕获可执行的 exe?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!