3

I have a simple FOR loop inside of a batch file I'm creating that isn't quite working the way I'm expecting. The FOR loop iterates through lines of a text file, and on each iteration, I use an IF statement to make a quick comparison on the current line, and do some work if it evaluates to true. Here is the code:

SETLOCAL ENABLEDELAYEDEXPANSION
set /a sitecounts=1
set /a input=34
FOR /F "tokens=1,2 delims=^/" %%G IN (file.txt) DO (
IF %sitecounts% == %input% (set /a selectedsitepath=%logfilepath%W3SVC%%H)
set /a sitecounts=!sitecounts!+1
echo !sitecounts!
)

I'm running into a weird issue where, the sitecounts variable (my counter) actually increments properly with each loop (I prove this by echoing out the count with the last statement) -- BUT upon the next iteration %sitecounts% still shows that it has the value of '1', which was the initial value.

If I change the code to:

IF !sitecounts! == ...

...then the IF statement appears to treat that value as pure TEXT! I've set ENABLEDELAYEDEXPANSION to handle variables within loops, but not sure what to do next. Any help is appreciated!

2
  • It might be worth learning PowerShell. Windows BAT files are quite limited. Commented May 4, 2012 at 17:58
  • While powershell may be worth learning, Windows batch scripts are easily up to this task. Commented May 7, 2012 at 22:34

2 Answers 2

2

This time I actually tested it....

Change the line

IF %sitecounts% == %input% (set /a selectedsitepath=%logfilepath%W3SVC%%H)

into

IF !sitecounts! == %input% (set selectedsitepath=%logfilepath%W3SVC%%H)
  • %sitecounts% needs to be !sitecounts! in order to be evaluated
  • set /a selectedsitepath=%logfilepath%W3SVC%%H doesn't work because it is not a numerical expression:

    The /A switch specifies that the string to the right of the equal sign is a numerical expression that is evaluated.

    Just omit the switch (/p is not going to work neither, that's for a prompt)

Sign up to request clarification or add additional context in comments.

Comments

0

Probably the error is in this line

IF %sitecounts% == %input% (set /a selectedsitepath=%logfilepath%W3SVC%%H)

you are setting a string not a numeric expression (set /a), then change to

IF !sitecounts! == %input% (set   selectedsitepath=%logfilepath%W3SVC%%H)
   ^          ^                 ^

2 Comments

Yes, the switch was the culprit, but replacing it by /p is not the solution: The /P switch allows you to set the value of a variable to a line of input entered by the user. In order to set a variable to a string value, no switch is needed.
@marapet right, just seen that /a /p in set help and thought that /p was for string. Answer updated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.