Dealing with %ERRORLEVEL%

by Dec 29, 2014

All PowerShell versions

When you run native EXE console commands inside your scripts, these commands typically return a numeric return value. This value is known as "ErrorLevel", and in batch files, you would refer to the return value as %ERRORLEVEL%.

Let's see how PowerShell gets a hold of this numeric return value, and how a PowerShell script can in turn emit its own "ErrorLevel" – that then could be received by the caller of the PowerShell script:

ping 1.2.3.4 -n 1 -w 500
$result1 = $LASTEXITCODE

ping 127.0.0.1 -n 1 -w 500
$result2 = $LASTEXITCODE

$result1
$result2

if ($result1 -eq 0 -and $result2 -eq 0)
{
  exit 0
}
else
{
  exit 1
} 

In this example, the code pings two IP addresses. The first call fails, the second succeeds. The script saves the return code through $LASTEXITCODE and saves it in two variables.

It then figures out what the impact of these return values are. In the example, the PowerShell script emits an ErrorLevel code of 0 if both calls returned 0, else it emits 1.

Of course, this is just a simple example. You can use it with your own native commands. Just make sure you save the value of $LASTEXITCODE immediately after the call of the native application, as it is overwritten by subsequent calls.

Twitter This Tip! ReTweet this Tip!