为什么不延迟扩展工作作为for命令中的参数

时间:2016-02-25 18:55:18

标签: batch-file command-line

我想为变量中提供的每个路径执行一些for循环。 echo !temp!工作正常,但是下面的for命令无法正常工作:

@echo off
setlocal enabledelayedexpansion

set paths=(C:\test C:\test2)

for %%p in %paths% do (
    set temp=%%p
    echo !temp!
    for /r !temp! %%f in (*.h) do (echo %%f)
    for /r !temp! %%g in (*.h *.cpp) do (echo %%g)
)

1 个答案:

答案 0 :(得分:3)

在所有for commands语法模式中:

  FOR %%parameter IN (set) DO command 
  FOR /R [[drive:]path] %%parameter IN (set) DO command 
  FOR /D %%parameter IN (folder_set) DO command 
  FOR /L %%parameter IN (start,step,end) DO command 
  FOR /F ["options"] %%parameter IN (filenameset) DO command 
  FOR /F ["options"] %%parameter IN ("Text string to process") DO command
  FOR /F ["options"] %%parameter IN ('command to process') DO command

%%parameter之前的所有文本都应在第一个解析阶段中知道。阅读How does the Windows Command Interpreter (CMD.EXE) parse scripts?

但是,下一个脚本应该按预期工作

@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
set "paths=(C:\test C:\test2)"

for %%p in %paths% do (
    set "temp=%%~p"
    echo !temp!
    call :doit
)

rem skip procedure
goto :domore

:doit
    for /r "%temp%" %%f in (*.h) do (echo %%f)
    for /r "%temp%" %%g in (*.h *.cpp) do (echo %%g)
goto :eof

:domore