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?
try / catchin 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.: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.