blogs.conchango.com

welcome to the conchango blogging site
Welcome to blogs.conchango.com Sign in | Join | Help
in Search

Merrick Chaffer's Blog

Resetting %ERRORLEVEL% in batch file programming

Came across a definite gotcha today in batch file programming, when I noticed that we had SET ERRORLEVEL=0 in one of our batch files. Turns out that once you set this variable explicitly then any command you run after will not be able to change the value of the %ERRORLEVEL% variable. E.G.

C:\>dir AUTOEXEC.BAT
Volume in drive C has no label.
Volume Serial Number is 907A-1111

Directory of C:\

02/08/2006  09:58                 0 AUTOEXEC.BAT
               1 File(s)              0 bytes
               0 Dir(s)  11,104,747,520 bytes free

C:\>echo %errorlevel%
0

C:\>dir lkksjdfljsdk
Volume in drive C has no label.
Volume Serial Number is 907A-1111

Directory of C:\

File Not Found

C:\>echo %errorlevel%
1

C:\>set errorlevel=0

Now you would expect the next rogue dir statement to set the errorlevel back to 1

C:\>dir lkksjdfljsdk
Volume in drive C has no label.
Volume Serial Number is 907A-1111

Directory of C:\

File Not Found

But as you can see it does not

C:\>echo %errorlevel%
0

A neat way to reset the error level is to just use the verify >nul command, as this works fine

C:\>dir sdkfljs
Volume in drive C has no label.
Volume Serial Number is 907A-1111

Directory of C:\

File Not Found

C:\>echo %errorlevel%
1

C:\>verify >nul

C:\>echo %errorlevel%
0

C:\>dir lskjlkj
Volume in drive C has no label.
Volume Serial Number is 907A-1111

Directory of C:\

File Not Found

C:\>echo %errorlevel%
1

C:\>

Published 28 February 2008 10:18 by merrick.chaffer
Filed under: , , , ,

Comments

No Comments
Anonymous comments are disabled
Powered by Community Server (Personal Edition), by Telligent Systems