Windows CMD Batch: FOR /R with DelayedExpansion

心不动则不痛 提交于 2019-12-05 15:55:00
jeb

Why FOR works different than ECHO is because the batch parser (cmd.exe) has special parsing rules for FOR, IF and REM.

Therefore delayed expansion doesn't work for the parameters here, only for the arguments inside the parenthesis.

Only percent expansion works for the parameters, as the parser executes the percent expansion phase just before it switches to the special FOR parser rules.

If you can't use percent expansion, as you are inside of a block you can move the code to an own function and call it.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET test="C:\Users\Tyler\Desktop\test"

ECHO !test!
call :doMyLoop test
exit /b

:doMyLoop
set "arg=!%1!"
FOR /R %arg% %%F IN (*) DO (
    ECHO %%F
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!