1.

Solve : unable to set a variable in a For loop?

Answer»

Hi, I am unable to set a varaible in a FOR LOOP.
I know this has something to do with SETLOCAL ENABLEDELAYEDEXPANSION
Here is the code:

Code: [Select]@ECHO OFF
cls
SETLOCAL ENABLEDELAYEDEXPANSION

for /f "tokens=1 delims=" %%S in (filename.txt) do (

echo EXECUTING FILE %%S
set file=%%S
echo file is : !file!
set syntaxterror=0
echo syntaxerror is: %syntaxerror%

type "output.txt" | find /i "Msg" && set syntaxerror=1
echo syntaxerror is: %syntaxerror%
REM if %syntaxerror% EQU 1 CALL :end !file!

)

echo "All Files executed successfully"
PAUSE

ENDLOCAL
exit

:end

echo "There was error executing the file: %1
pause
ENDLOCAL
exit

For now just assume filename.txt has a few lines of code and I execute them one by one.
Also the contents of output.txt could be something like this:
Msg 102, Level 15, State 1:

However what my REAL problem is, I am unable to set the variable syntaxerror

Is there something I am doing wrong?Aneways I found the solution myself. Redirected to a new loop outside the For loop and it worked.

I am POSTING the code, It might help someone else.

Code: [Select]@ECHO OFF
cls
SETLOCAL ENABLEDELAYEDEXPANSION

for /f "tokens=1 delims=" %%S in (sqlfile.txt) do (

echo EXECUTING FILE %%S
set file=%%S
echo file is : !file!
set syntaxterror=0
echo syntaxerror is: %syntaxerror%
CALL :loop !file!

)

echo "All Files executed successfully"
pause
ENDLOCAL
exit


:end

echo "There was error executing the file: %1
pause
ENDLOCAL
exit


:loop
set syntaxerror=0
type "output.txt" | find /i "Msg" && set syntaxerror=1
echo syntaxerror is: %syntaxerror%
if %syntaxerror% EQU 1 CALL :end %1
Still could someone tell me why can't I set a variable in a For loop?

Many thanks!!wich variable? This code look good Code: [Select]set syntaxterror=0
echo syntaxerror is: %syntaxerror%

type "output.txt" | find /i "Msg" && set syntaxerror=1
echo syntaxerror is: %syntaxerror%
REM if %syntaxerror% EQU 1 CALL :end !file!
Change %syntaxerror% to !syntaxerror!

So the delayed expansion will apply.

You did it for the other variables, but you missed that one.



Discussion

No Comment Found