Errorlevel in a For loop (batch windows)

user461487 picture user461487 · Oct 15, 2010 · Viewed 36.3k times · Source

I have the following windows batch code:

for %%i in (iidbms iigcc iigcd dmfacp dmfrcp rmcmd qwerty) do (
  tasklist | findstr /i %%i
  echo %errorlevel%
  if %errorlevel% == 0 (echo %%i ok process found %errorlevel%)
  if %errorlevel% == 1 (echo %%i no process found %errorlevel%)
)

But it doesn't work as I expect.

All the name processes iidbms, iigcc, iigcd, dmfacp, dmfrcp, rmcmd are real, and they are found, instead qwerty is an invented one and should not find it, so should print " no process found 1", but it doesn't, it always prints 0.

But what I have noted is that if I run the tasklist | findstr /i qwerty from the dos prompt, just after there is that the %errorlevel% = 1.

What sort of answer could be or better is?

Answer

Tim Abell picture Tim Abell · Jul 27, 2012

Add

setlocal EnableDelayedExpansion

to the start of your script, then use !errorlevel! instead of %errorlevel%

Delayed Expansion will cause variables to be expanded at execution time rather than at parse time

~ http://ss64.com/nt/delayedexpansion.html

The answer to another question that pointed me in the right direction: https://stackoverflow.com/a/6658935/10245