Catching Errors in Native EXEs (Part 2)

by Dec 19, 2014

All versions

Here is yet another approach that you can use to detect errors emitted by console applications:

$ErrorActionPreference = 'Continue'
$result = net.exe user UserDoesNotExist 2>&1 

# $? is $false when something went wrong
if ($? -eq $false) {
    # read last error:
    $errMsg = $result.Exception.Message -join ','
    Write-Host "Something went wrong: $errMsg"
} else {
    Write-Host 'All is fine.'
} 

Note the use of $ErrorActionPreference: when it is set to ‘Stop’, the error would be converted into a .NET exception. The default setting for $ErrorActionPreference is ‘Continue’. With this setting, the script can receive the error in $err.

The built-in variable $? Returns $false if the last call fails. In this case, the code returns an error message (or could do other things, like adding information to a log file).

Twitter This Tip! ReTweet this Tip!