Page 1 of 1

Code will not iterate through file

Posted: 12 Dec 2011 15:20
by tiggyboo
I have a script designed to read a text file and make parameters of the elements of each line, then act on them. However, it just returns info for the last line for as many times as there are lines in the input file. Here's the code:

Code: Select all

@Echo Off
setlocal EnableDelayedExpansion
Set _InputFile=master.txt
For /F "tokens=1-6 delims=|" %%A IN (%_InputFile%) DO (
Set _server=%%A
Set _database=%%B
Set _username=%%C
Set _pwd=%%D
Set _name=%%E
Set _type=%%F
echo Processing %_server%

if "%_type%"=="s" (
[do stuff...]
) else (
[do stuff...])
)


And here's an example input file:

Code: Select all

servera|dba|usera|xxx|DM|s
serverb|dbb|userb|yyy|PMT|m


And the output:

Code: Select all

Processing dbb
Processing dbb


I figure it must be the parameters in the for command, but I can't get it to work for the life of me... any suggestings very appreciated!

Regards, Al

Re: Code will not iterate through file

Posted: 12 Dec 2011 15:48
by dbenham
This has got to be one of the most common recurring problems with people new to batch programming.

With FOR ... IN(...) DO (.....), everything is logically treated as one line and so %VAR% is expanded only once. The value will be constant throughout the lifetime of the loop, and the value will be the value that existed prior to to execution of the loop.

The solution is to use !VAR! delayed expansion instead. Delayed expansion expands the variable at execution time instead of parse time. Delayed expansion enables you to access variables values that were assigned within the loop.

To use delayed expansion you must first enable it, usually near the top of your script.

Code: Select all

setlocal enableDelayedExpansion
...
for.... do(
  ...
  set var=%%A
  ...
  if "!var!"=="value" ....
  ...
)

There can be unintended side-effects when delayed expansion is enabled, and there are various strategies to deal with them. But this is enough to get you started.

Dave Benham

Re: Code will not iterate through file

Posted: 12 Dec 2011 16:00
by tiggyboo
Thanks very much Dave. I guess I was headed in the right direction since I had the setlocal enableDelayedExpansion in place, but it was all for naught since I was still using the %'s. Thanks again!