batch file errorlevel set to 0 on startup

901 views Asked by At

The errorlevel as soon as the .bat file is run is 0. However I am using errorlevel as a condition such as:

REG Query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall\test 2>NUL>>MMG.dat
If %ERRORLEVEL% == 0 goto turnon

REG Query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall\test2>NUL>>MMG.dat
If %ERRORLEVEL% == 0 goto turnon

REG Query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall\test 3>NUL>>MMG.dat
If %ERRORLEVEL% == 0 goto turnon
If %ERRORLEVEL% == 1 goto EOF

My problem is that if the errorlevel is already set to 0 then the condition becomes invalid.

Is their anyway I can work around this?

Note: errorlevel is NOT set anywhere within the file.

I am learning this language so please bear with me if its an obvious mistake

Thanks

1

There are 1 answers

8
paxdiablo On

I seem to recall that it's a bad idea to actually use the %errorlevel% variable itself for a variety of reasons, among them the fact it can be set manually which disconnects it from the actual return codes. For more detail, see this item on Rob van der Woude's scripting pages, a valuable resource for all things scripting under Windows/DOS.

You should be using something like:

if errorlevel 1 ...

However, I'm not entirely certain what you're considering to be incorrect here. Yes, %errorlevel% may be set to zero before the script starts but that will be changed by the first call to reg, which will set it to 0 on success or 1 on failure.

If your intent is to do something should the reg query fail, simply use:

reg query 1 blah blah blah
if errorlevel 1 goto turnon

reg query 2 yak yak yak
if errorlevel 1 goto turnon

reg query 1 bjork brork bjork
if errorlevel 1 goto turnon

If it's to do something (like alert on any failing as per your question/comment) then what you have is okay, just with slightly different method and value:

set bad=0

reg query 1 blah blah blah
if errorlevel 1 goto alert

reg query 2 yak yak yak
if errorlevel 1 goto alert

reg query 1 bjork brork bjork
if errorlevel 1 goto alert

rem all queries returned success.