Reputation: 25928
I have a very weird error occurring in my Batch script where a For
loop is only looping once when it should loop many more times (at least 10 times).
Can you tell me why my For
loop is only looping once and how I can fix it?
@ECHO off
CLS
SETLOCAL
SET macroFolder=_PLACE_4DM_FILES_HERE
REM the following for loop only loops once when it should be looping more
REM because theres over 10 *.4dm files in the folder??
for /r ./%macroFolder% %%i in ("*.4dm") do SET "file=%%i" (
echo %file%
REM Note I need to store %%i in a variable so I can edit it later
REM And placing %%i in a variable within the for loop results in
REM the var being empty for some reason. For eg
SET file=%%i
ECHO file is %file%
REM Prints "file is "
)
ECHO.
PAUSE
ENDLOCAL
Upvotes: 0
Views: 1336
Reputation: 881653
You have (at least) two problems. The first is that you seem to be mixing the bracketed and non-bracketed form of the for
statement:
for /r ./%macroFolder% %%i in ("*.4dm") do SET "file=%%i" (
blah blah
)
In that case, the non-bracketed bit is executed per-loop-iteration but the bracketed bit executes after loop exit. You can see this with:
for /r ./%macroFolder% %%i in ("*.4dm") do echo 1 (
echo 2
)
which outputs (in my case where there are three 4dm
files):
1 (
1 (
1 (
2
Your second problem is that %%
variable expansion is done before the command executed and the for
command is a multi-line one, from the for
to the closing )
bracket. Any variables you need expanded, that have been set within the loop, need to be done with delayed expansion.
Start with this:
@SETLOCAL enableextensions enabledelayedexpansion
@ECHO off
CLS
SET macroFolder=4dmfiles
for /r ./%macroFolder% %%i in ("*.4dm") do (
SET file=%%i
ECHO file is !file!
)
ECHO.
PAUSE
ENDLOCAL
and you'll see (for my three files):
file is C:\Users\Pax\Documents\4dmfiles\1.4dm
file is C:\Users\Pax\Documents\4dmfiles\2.4dm
file is C:\Users\Pax\Documents\4dmfiles\3.4dm
Upvotes: 5