Almost all applications and utilities will set an exit code when they complete/terminate.

The exit codes that are set do vary, in general a code of 0 (false) will indicate successful completion.

The exit codes set by resource kit utilities are not always consistent, they can vary between machines with different Service packs/Resource kit updates applied.

Some utilities will return negative numbers as an exit code.

In the CMD shell the exit code is made available via the %ERRORLEVEL% variable or via IF ERRORLEVEL ...

IF ERRORLEVEL n statements should be read as IF Errorlevel >= number
IF ERRORLEVEL 1 will return TRUE when the ERRORLEVEL is greater than or equal to 1

IF NOT ERRORLEVEL 1 means if ERRORLEVEL is less than 1 (Zero or negative).

You should never attempt to write to the %ERRORLEVEL% variable because the value you set will then take precedence over the internal ERRORLEVEL.

Batch files

You can make a batch file return a non-zero exit code by using the EXIT command.

To force an ERRORLEVEL of 1 to be set, run a small but invalid command like COLOR 00
or to speciy a particular ERRORLEVEL run CMD /C Exit /B 5

There is one difference between the way .CMD and .BAT batch files set errorlevels:


In PowerShell $? contains True if last operation succeeded and False otherwise.

The exit code of the last Win32 executable execution is stored in the automatic variable $LASTEXITCODE

To read exit codes (other than 0 or 1) launch the PowerShell script and return the $LASTEXITCODE in a single line like this:

powershell.exe -noprofile C:\scripts\script.ps1; exit $LASTEXITCODE

“I’d rather wake up in the middle of nowhere than in any city on earth” ~ Steve McQueen


Robocopy exit codes

© Copyright SS64.com 1999-2016
Some rights reserved