DOS Batch File Error Level Checking Tricks...
Jun 28, 2012 by Jeremy.Pavlov
Fellow Coreteker Paul and I were chatting today about capturing post-execution error codes in Windows. Paul was looking to grab the error code resulting from a script (VBscript, if I recall), and he was looking for the best way. He found a handy way to handle it (pun intended); but it left me thinking about how one might capture error codes *within* a DOS batch file, and how that might be tricky. So I tossed a few notes together and I thought I'd pass them along to you...
First things first: the DOS post-execution error code is stored in the dynamic variable
One of the important things to remember when trying to grab error codes from DOS batch files is that each executed line of the batch file will produce its own error code result, as well as the fact that you have the capability to grab the error code of the script as a whole (by issuing an
EXIT /B command). Note that one must never hard-set an error level, as you'll break the shell's ability to dynamically manage the variable.
So, if you have multiple lines in your script and wish to capture the error codes from some of the lines, here are a few suggestions...
IF %ERRORLEVEL% EQU 0 SET RESULT=YUUUP
...this will grab your error code and just for fun set your
%RESULT% to the now-famous trademarked "Storage Wars" catch phrase (minus the exclamation point for legal). You'd typically run this line after the previous line from which you wanted to capture the code. Error code of zero almost always means that it is operating as intended.
However, to catch unintended errors in either of these cases,
IF %ERRORLEVEL% NEQ 0 SET RESULT=%ERRORLEVEL%
IF %ERRORLEVEL% EQU 1 SET RESULT=%ERRORLEVEL%
...they will both will grab the error code, check to see if it's not equal to zero, and set the
%RESULT% variable with the code it grabbed. Note that the second line -- while checking for a value of 1 -- is actually checking for 1 or more; this is default behavior.
After grabbing the error code and evaluating it, you can have the script have success/failure-specific condition statements act upon the condition (send notice, add to the event log, exit, etc.).
I hope that helps!