Using "for" command in a batch file

C

Chris

I'm not sure if this is the right newsgroup -- please let me know if
there is a better one.

I'm trying to construct an environment variable that contains a list of
all the files in a directory. Something like this:

for %%f in (mydir\*.txt) DO set mylist=%mylist%;%%f

This should be equivalent to "set mylist=;file1.txt;file2.txt;file3.txt"

Instead I get "mylist=;file3.txt"

It doesn't seem to be updating the mylist variable on each loop.
Instead, it just saves the value on the last loop.

What am I doing wrong?
 
P

Pegasus \(MVP\)

Chris said:
I'm not sure if this is the right newsgroup -- please let me know if
there is a better one.

I'm trying to construct an environment variable that contains a list of
all the files in a directory. Something like this:

for %%f in (mydir\*.txt) DO set mylist=%mylist%;%%f

This should be equivalent to "set mylist=;file1.txt;file2.txt;file3.txt"

Instead I get "mylist=;file3.txt"

It doesn't seem to be updating the mylist variable on each loop.
Instead, it just saves the value on the last loop.

What am I doing wrong?

By default each line of a batch file is scanned once to resolve
its environmental variables. You need to scan in each time
you run through the loop. Try the following version:
@echo off
setlocal enabledelayedexpansion
set MyList=
set Separator=
for %%a in (*.txt) do (
set MyList=!MyList!!Separator!%%a
set Separator=,
)
echo %MyList%
endlocal

Run for /? from a Command Prompt to get the documentation
on this technique
 
A

Anon E. Mouse

Pegasus said:
By default each line of a batch file is scanned once to resolve
its environmental variables. You need to scan in each time
you run through the loop. Try the following version:
@echo off
setlocal enabledelayedexpansion
set MyList=
set Separator=
for %%a in (*.txt) do (
set MyList=!MyList!!Separator!%%a
set Separator=,
)
echo %MyList%
endlocal

Run for /? from a Command Prompt to get the documentation
on this technique
Thanks. That worked perfectly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top