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.
When ending a subroutine, you can use EXIT /b N to set a specific errorlevel N.
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.
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:
An old .BAT batch script running the 'new' internal commands: APPEND, ASSOC, PATH, PROMPT, FTYPE and SET will only set ERRORLEVEL if an error occurs. So if you have two commands in the batch script and the first fails, the ERRORLEVEL will remain set even after the second command succeeds.
This can make debugging a problem BAT script more difficult, a CMD batch script is more consistent and will set ERRORLEVEL after every command that you run [source].
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