FOR /F command and ERRORLEVEL

Microsoft Windows vista ultimate w/ sp1...
April 6, 2010 at 06:59:44
Specs: Windows Vista Ultimate SP2, 3GB
Hi, I was just wondoering, is there a way of getting the errorlevel from a command given to the FOR /F command? Example:

setlocal enabledelayedexpansion
cmd /c exit 1
echo !errorlevel! (shows 1 as expected)
for /f "delims=" %%a in ('cmd /c exit 2') do (
   echo !errorlevel! (not executed as loop done 0 times)
echo !errorlevel! (still 1, not 2)

Any ideas?

See More: FOR /F command and ERRORLEVEL

Report •

April 6, 2010 at 09:02:46
the only way i know is to put it inside another batchfile which then writes the %errorlevel% out to a tempfile:
for /f %%a in ('test.bat') do echo done
for /f %%a in ('test.out') do echo error was %%a
cmd /c "exit 2"
echo %errorlevel% > test.out
::--- done
there's just not much of a communications link to go with.

Report •

April 6, 2010 at 10:55:28
For programmer readability, I would propose to run the actual command (before using it in the FOR loop), examine the errorcode, act on it, then go on with rest (which may include running the same command in a FOR loop, depening on errorlevel found out already).

It will create more commands, but it will be easier to debug later.

Report •

April 7, 2010 at 02:30:46
Thanks for the ideas. So as I suspected and as you both say, there's no direct way of getting the errorlevel from inside the for /f command, but you have to use workarounds.

Report •

Related Solutions

Ask Question