问题
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