1.

Solve : ERRORLEVEL = 0 within FOR loop?

Answer»

I have posted previously about my DR check batch file, but just one issue remains...

I have this code within the batch...

example.txt contains the following line for testing...
Quote

\autoexec.bat

The for loop contains; - I changed the FIND to wwwwwwww to force a failure.
Code: [Select]set TIB=example.txt
set SERVER=C:
for /f "eol=; tokens=* delims=" %%i in (%TIB%) do (
dir "%SERVER%%%i" | find "wwwwwwww" >nul
if %ERRORLEVEL%==0 (
echo Located - %SERVER%%%i >> %logfile%
) ELSE (
echo ***ERROR*** - %SERVER%%%i, does not exist or incorrect file date >> %logfile%
)
)

For some reason ERRORLEVEL always RETURNS zero even if the file doesn't exist, I'm assuming that's because the FOR command didn't error even though the dir command did.
If I run the DIR command outside the FOR loop it returns errorlevel 1

Does ANYBODY know of a way around this?you can try

Code: [Select]set TIB=example.txt
set SERVER=C:
for /f "eol=; tokens=* delims=" %%i in (%TIB%) do (
dir "%SERVER%%%i" | find "wwwwwwww" >nul
if ERRORLEVEL 1 (
echo ***ERROR*** - %SERVER%%%i, does not exist or incorrect file date >> %logfile%
) else (
echo Located - %SERVER%%%i >> %logfile%

)
)

Or:
setlocal enabledelayedexpansion
set TIB=example.txt
set SERVER=C:
for /f "eol=; tokens=* delims=" %%i in (%TIB%) do (
dir "%SERVER%%%i" | find "wwwwwwww" >nul
if %ERRORLEVEL%==0 (
echo Located - %SERVER%%%i >> %logfile%
) else (
echo ***ERROR*** - %SERVER%%%i, does not exist or incorrect file date >> %logfile%
)
)
endlocaltry this

variables set and read inside parenthetical expressions need delayed expansion.

setlocal enabledelayedexpansion
set TIB=example.txt
set SERVER=C:
for /f "eol=; tokens=* delims=" %%i in (%TIB%) do (
dir "%SERVER%%%i" | find "wwwwwwww" >nul
if !ERRORLEVEL! EQU 0 (
echo Located - %SERVER%%%i >> %logfile%
) else (
echo ***ERROR*** - %SERVER%%%i, does not exist or incorrect file date >> %logfile%
)
)
Thanks, not quite correct but you gave me a good pointer...

I just needed to replace % with !...
Code: [Select]if !ERRORLEVEL!==0
setlocal command was already added but not included it in my post above

I've noticed another issue, but I'll create a new post Quote from: ShadyDave on April 29, 2010, 07:39:36 AM
not quite correct

Code: [Select]if !ERRORLEVEL!==0
Code: [Select]if !ERRORLEVEL! EQU 0
These two are equivalent; I don't understand why you call my VERSION "not quite correct".
It created an error USING the EQU for some reason :-(Quote from: ShadyDave on April 29, 2010, 04:12:13 PM
It created an error using the EQU for some reason :-(
What was the line?
If !ERRORLEVEL! EQU 0 echo There was no error...

should work properly.Quote from: Helpmeh on April 29, 2010, 06:11:31 PM
What was the line?
If !ERRORLEVEL! EQU 0 echo There was no error...

should work properly.

It works properly for me.


Discussion

No Comment Found