Wednesday, October 28, 2009

Errorlevel: Checking for Errors while Executing a Batch Script

Sometimes it's necessary to check for errors while executing a batch script. Command interpreter has built-in support for storing the return code of the command or program most recently executed. Note: error level is not a variable from the point of a batch script writer. You can't check it with the following code:
If %Errorlevel%==1 goto Error
You should write instead this line:
If Errorlevel 1 goto Error
You can't check whether error level equals to zero or other defined value. "If errorlevel" executes the command following this statement if error level is equal or greater than the specified value. This strange syntax is very handy because usually you don't have to check the error level for any value except zero. So using this construction you avoid checking for a large amount of different values.
Though you can use alternative syntax that also works:
If %Errorlevel% NEQ 0 goto Error
Here you can see that error level is used like a variable. But it's a fake variable. You can't use it in any other way except the way shown above. Note: this code works only under Windows NT family operating systems (NT 4.0, 2000, XP, etc.). So if you need to write MS-DOS-compatible batch file, you have to use "If errorlevel" command.

No comments:

Post a Comment

Translate