I want to make a batch file, that would make me happy a long string of all file names in the directory.
So I have a directory:
-docA.pdf
-docB.pdf
-docC.pdf
And I want to have a string like this:
docA.pdf docB.pdf docC.pdf
In a nutshell:
http://bit.ly/u1eAHO
Long way:
I wrote a script
@echo off
pushd "%~dp0"
set "FILE_LIST=pre_"
FOR /F "tokens=*" %%i IN ('DIR /A:-D /B') DO (
IF NOT %%i==%~nx0 (
echo %%i
set "FILE_LIST=%FILE_LIST%%%i"
echo %FILE_LIST%
)
)
echo %FILE_LIST%
pause
And get this output:
docA.pdf
pre_
docB.pdf
pre_
docC.pdf
pre_
pre_docC.pdf
Why? How can I get the good one?
This is a pretty well-known problem with batch files. The short answer is that batch files are executed by expanding the variables in a line before executing them. For multiline blocks (the stuff in parentheses) have all of the non-loop variables expanded once and then the loop is run. Your loop body is essentially:
They added a feature called delayed expansion somewhere along the way (NT4 IIRC) that you can enable in the registry or via a
SETLOCALstatement. Change your script to something like:and it should work. I’m away from my Windows box until Monday, but that should be close enough. If you run into any problems read the help shown by typing
FOR /?andSETLOCAL /?in a command prompt.