Showing posts with label errors handling. Show all posts
Showing posts with label errors handling. Show all posts

Thursday, January 10, 2013

What is errorlevel?



 Sooner or later every batch files creator faces the problem of checking the result of one command execution before executing the other one. For that we have built-in variable “errorlevel” that changes its value after each command execution. Its value can vary for different commands used in batch files. Usually successful execution of the command is displayed as zero value of variable, but not always other value implies any errors. So if you create batch file, you should remember about this meaning of errorlevel.
This variable is used as follows:
if errorlevel 0 echo Errorlevel is 0 or greater
Instead of “echo Errorlevel is 0 or greater” you can put any necessary command. After “if” you can add “not” (no quotation marks for this time again) – then the value becomes diametrically opposed. It should be mentioned that “errorlevel N”-construction does not mean precise equality of variable “errorlevel” to value N. It means that the command will be executed only in case “errorlevel” value is or is greater than N. Thus it is more convenient to check errors with the help of “if errorlevel” –construction than to execute the command successfully. But if you write “if not errorlevel 1”, that means in case “errorlevel” is nonnegative, we obtain the result of “errorlevel” equal to zero. Unfortunately nonnegative values of this variable are not guaranteed. For more details you can read about “if errorlevel” –construction in Windows help manual.

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.

Translate