Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try Catch on executable exe in Powershell?

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?

like image 411
JBurace Avatar asked Sep 10 '12 21:09

JBurace


People also ask

How do you use try and catch in PowerShell?

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.

Does try catch stop execution PowerShell?

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.

What do you know about try catch in PowerShell?

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.


1 Answers

> 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
like image 93
Marc Avatar answered Sep 21 '22 20:09

Marc