Try Catch on executable exe in Powershell?

不羁岁月 提交于 2019-12-18 03:17:07

问题


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

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.

How would I catch errors?


回答1:


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
}

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.



来源:https://stackoverflow.com/questions/12359427/try-catch-on-executable-exe-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!