1.

Solve : FOR /F command with DO SET /A, nested within IF?

Answer»

This is the problematic area of a larger batch file I am writing:

Code: [Select]ECHO 14 >TEMP.txt
FOR /F %%j in (TEMP.txt) DO SET /A CHOOSE=(%RANDOM%)%(%%j)
ECHO %CHOOSE%
PAUSE
I get the error "Missing operator." The denominator of the modulus operator is not resolving correctly.

Thanks in advance for any help you may be able to provide.

P.S. Sigh...I answered my own question. The line in question is more correctly:

Code: [Select]FOR /F %%j in (TEMP.txt) DO SET /A CHOOSE=(%RANDOM%)%%(%%%j)
Posted FYI anywayThe problem re-occurs when the above (working) sample is further nested in an IF statement as follows:

Code: [Select]SETLOCAL EnableDelayedExpansion
FOR /L %%i in (1,1,10) DO IF %%i LEQ 5 (
ECHO 14 >TEMP.txt
FOR /F %%j in (TEMP.txt) DO SET /A CHOOSE=(%RANDOM%)%%(%%%j)
)
ECHO %CHOOSE%
PAUSE

The error displayed is "%(%j) was unexpected at this time."

Changing the problematic line as follows:

Code: [Select]FOR/F %%j in (TEMP.txt) DO SET /A CHOOSE=(%RANDOM%)%%(!j)


results in the error "%(!j) was unexpected at this time."

How am I to invoke run-time evaluation for the nested FOR variable %%j?

Again, thanks in advance for any help you may be able to provide.Quote from: John_L. on January 03, 2013, 01:40:23 PM

The problem re-occurs when the above (working) sample is further nested in an IF statement as follows:

Code: [Select]SETLOCAL EnableDelayedExpansion
FOR /L %%i in (1,1,10) DO IF %%i LEQ 5 (
ECHO 14 >TEMP.txt
FOR /F %%j in (TEMP.txt) DO SET /A CHOOSE=(%RANDOM%)%%(%%%j)
)
ECHO %CHOOSE%
PAUSE

The error displayed is "%(%j) was unexpected at this time."

Changing the problematic line as follows:

Code: [Select]FOR/F %%j in (TEMP.txt) DO SET /A CHOOSE=(%RANDOM%)%%(!j)


results in the error "%(!j) was unexpected at this time."

How am I to invoke run-time evaluation for the nested FOR variable %%j?

Again, thanks in advance for any help you may be able to provide.
Of COURSE you will get that error. You don't USE an exclamation to expand a token! Delayed Expansion does not work with tokens nor is it needed.

Your code seems very very odd to me. I don't KNOW why you are doing what you are doing. The code is extremely inefficient and doesn't seem to serve a practical purpose.

Could you explain what you are really trying to accomplish? Not really understanding why you are doing what you are doing with a lot of your code. Why echo a number to a text file and then read it back in with a FOR /F loop? Why would you create a loop for 10 and then only execute code if the number is LEQ to 5.

Regardless I think this is what you are trying to do.
Code: [Select]@echo off
SETLOCAL EnableDelayedExpansion
FOR /L %%i in (1,1,10) DO IF %%i LEQ 5 (
ECHO 14 >TEMP.txt
FOR /F %%j in (TEMP.txt) DO SET /A CHOOSE=!RANDOM! %% %%j
echo !CHOOSE!
)
PAUSE


Discussion

No Comment Found