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?
Powershell Try Catch Finally Try { # Try something that could cause an error 1/0 } Catch { # Catch any error Write-Host "An error occurred" } Finally { # [Optional] Run this part always Write-Host "cleaning up ..." } In the Try block, you place the script that could cause an error.
Try-Catch will catch an exception and allow you to handle it, and perhaps handling it means to stop execution... but it won't do that implicitly. It will actually consume the exception, unless you rethrow it.
Try/Catch block in PowerShell is to handle the errors which are produced in the script. To be specific, the errors should be terminating errors. The Finally block in the PowerShell is not mandatory to write each time along with Try/Catch but it will be executed regardless the error occurs or not.
> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With