Catching Errors from Native EXEs

by Nov 30, 2016

Ever wondered how you can catch errors emitted by native console EXEs? PowerShell’s error handlers can only deal with .NET code.

Here is the framework to use when you’d like to catch console application errors:

try
{
    # set the preference to STOP
    $old = $ErrorActionPreference
    $ErrorActionPreference = 'Stop'
    # RUN THE CONSOLE EXE THAT MIGHT EMIT AN ERROR,
    # and redirect the error channel #2 to the
    # output channel #1
    net user doesnotexist 2>&1
}

catch [System.Management.Automation.RemoteException]
{
    # catch the error emitted by the EXE,
    # and do what you want
    $errmsg = $_.Exception.Message
    Write-Warning $errmsg
}

finally
{
    # reset the erroractionpreference to what it was before
    $ErrorActionPreference = $old
}

Whenever the console application emits an error, it goes through console output channel #2. Since this channel is redirected to the regular output in the example above, PowerShell receives it. Whenever the ErrorActionPreference is set to “Stop”, PowerShell turns any input from that channel into a .NET RemoteException that you can catch.

 
WARNING: The user name  could not be found.

Twitter This Tip! ReTweet this Tip!