Try Catch on executable exe in Powershell?
> try / catch in PowerShell doesn't work with native executables.
Actually it does, but only if you use "$ErrorActionPreference = 'Stop'" AND append "2>&1".
See "Handling Native Commands" / Tobias Weltner at https://community.idera.com/database-tools/powershell/powertips/b/ebookv2/posts/chapter-11-error-handling.
E.g.
$ErrorActionPreference = 'Stop'
Try
{
$output = C:\psftp.exe ftp.blah.com 2>&1
}
Catch
{
echo "ERROR: "
echo $output
return
}
echo "DONE: "
echo $output
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.