0

我的批处理脚本中发生了一个非常奇怪的错误,其中一个For循环只循环一次,而它应该循环更多次(至少 10 次)。

你能告诉我为什么我的For循环只循环一次以及如何修复它吗?

@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
4

1 回答 1

5

你有(至少)两个问题。首先是您似乎混合了for语句的括号和非括号形式:

for /r ./%macroFolder% %%i in ("*.4dm") do SET "file=%%i" (
    blah blah
)

在这种情况下,非括号位在每个循环迭代中执行,但括号位在循环退出后执行。你可以看到这个:

for /r ./%macroFolder% %%i in ("*.4dm") do echo 1 (
    echo 2
)

哪个输出(在我的情况下有三个4dm文件):

1 (
1 (
1 (
2

您的第二个问题是%%变量扩展是在命令执行之前完成的,并且for命令是多行的,从for到右)括号。您需要扩展的任何变量,已循环中设置,都需要延迟扩展。

从这个开始:

@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

你会看到(对于我的三个文件):

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
于 2013-05-23T04:44:28.240 回答