Errorlevel and Exit codes

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.
By default SCCM will only consider 0 a success, but commands like Robocopy may return success Exit Codes from 0 to 7.

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.

If you attempt to execute a non-existent command %ERRORLEVEL% will be set to 9009

Detecting Errorlevels

There are two different methods of checking an errorlevel, the first syntax provides compatibility with old .bat batch files from the era of MS-DOS

The errorlevel is made available via IF ERRORLEVEL ... or the %ERRORLEVEL% system variable.

IF ERRORLEVEL n statements should be read as IF Errorlevel >= number
i.e.
IF ERRORLEVEL 0 will return TRUE whether the errorlevel is 0, 1 or 5 or 64
IF ERRORLEVEL 1 will return TRUE whether the errorlevel is 1 or 5 or 64
IF NOT ERRORLEVEL 3 means if ERRORLEVEL is less than 3 ( 2, 1, 0 or a negative number).

To check for a specific error level N, you can use the following construct:

IF ERRORLEVEL N IF NOT ERRORLEVEL N+1 COMMAND

This is not very readable or user friendly and does not account for negative error numbers.

A preferred method of checking Errorlevels is to use the %ERRORLEVEL% system variable:

IF %ERRORLEVEL% NEQ 0 Echo An error was found
IF %ERRORLEVEL% EQU 0 Echo No error found

IF %ERRORLEVEL% EQU 0 (Echo No error found) ELSE (Echo An error was found)
IF %ERRORLEVEL% EQU 0 Echo No error found || Echo An error was found

This allows you to trap errors that can be negative numbers, you can also test for specific errors:
IF %ERRORLEVEL% EQU 64 ...

When ending a subroutine, you can use EXIT /b N to set a specific ERRORLEVEL N.

Raymond Chen [MSFT] explains: ERRORLEVEL is not the same as the %ERRORLEVEL% environment variable.

Error Message/Error Stream

In addition to setting an ERRORLEVEL, many utilities will output an error message on the error stream (STDERR), by default these messages will appear on the console, but they can be redirected with 2>.

Many utilities set an ERRORLEVEL and also output some error text, some utilities set an ERRORLEVEL but don’t display error text and some will display error text without setting an ERRORLEVEL. Some utilities behave differently depending on the severity of the error.

Error messages are likely to be different for each language/locale so it is generally more robust to just test the ERRORLEVEL rather than any text message output.

Error level vs Exit code

When an external command is run by CMD.EXE, it will detect the executable's Return or Exit Code and set the %ERRORLEVEL% to match.
In the majority of cases command extensions are enabled and so the %ERRORLEVEL% will be the same as the Exit code. It is possible to break this by manually creating a user variable called %ERRORLEVEL%.

An Exit Code can be detected directly with redirection operators Success=0 or Failure<>0. This is equivalent to IF ERRORLEVEL 1.

Old style .bat Batch files vs .cmd Batch scripts.

Although the differences are minor, there are no advantages to the .BAT extension, so I recommend using .CMD exclusively.

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

A .CMD batch script will set/reset the ERRORLEVEL after every command that you run [source] Mark Zbikowski (MSFT).

A .BAT batch script running the internal commands: APPEND, ASSOC, PATH, PROMPT, FTYPE and SET will only change the ERRORLEVEL if an error occurs. Other internal and external commands do not follow this rule.

So if you have two commands in a .BAT script and the first command fails but the second succeeds, the ERRORLEVEL may or may not remain set depending on which command was run.

This lack of consistency in the ERRORLEVELs raised makes debugging a .BAT script more difficult than an equlvalent .CMD script.

Even in the CMD shell, some commands don’t follow the rules

Even though a CMD batch script should set or reset ERRORLEVEL after every command, there are a few exceptions:

Commands that do NOT affect the ERRORLEVEL:
BREAK, ECHO, ENDLOCAL, FOR, IF, PAUSE, REM, RD/RMDIR, TITLE

Commands that will set but not clear an ERRORLEVEL:
CLS, GOTO, KEYS, POPD, SHIFT

Commands that set an Exit Code but not the ERRORLEVEL:
RD/RMDIR

Commands that set an ERRORLEVEL but not the Exit Code (SO explanation):
MD/MKDIR

Set or Force an exit code

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

Exit 0
Exit /B 5

To force an ERRORLEVEL of 1 to be set without exiting, run a small but invalid command like COLOR 00 or run (CALL) which does nothing other than set the ERRORLEVEL to 1.

To clear the ERRORLEVEL back to 0, run (call ), which does nothing except set the ERRORLEVEL to 0.

You should never attempt to SET the %ERRORLEVEL% because that will create a user variable named %ERRORLEVEL% which then takes precedence over the internal pseudo variable %ERRORLEVEL%.
You can clear any such user variable with the following command but really the best practice is to never set a variable with that name in the first place:
Set "errorlevel="

PowerShell

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

Related commands

Robocopy exit codes
Conditional Execution - if command1 succeeds then execute command2
HowTo: Error Handling in a batch file
List of ERRORLEVEL values set by internal cmd.exe commands - Stackoverflow /Aacini.
ERRORLEVEL is not %ERRORLEVEL% - The old new thing blog.


 
Copyright © 1999-2024 SS64.com
Some rights reserved