批处理文件For循环不扩展变量

时间:2016-06-13 14:39:11

标签: batch-file

我正在制作一个蝙蝠脚本,该脚本应该在一些构建工件周围移动。我需要它来循环几个不同的值(下面表示为ABCDEFGHI)。我还想在此过程中创建临时环境变量。但是,循环内部引入的环境变量不会得到扩展。

@echo on

setlocal EnableDelayedExpansion

:: Remove the OutputMSI directory
set output=OutputMSI

for %%x in (ABC DEF GHI) do (
    :: Create a new Output tree
    set products_dir=%output%\%%x\products
    mkdir %products_dir%

    :: Copy published files
    robocopy publish\%%x\ %products_dir% *.application *.deploy /s

    :: Copy Version.txt
    copy Version.txt %products_dir%
)

endlocal

这是回应的内容(内联评论):

C:\...>setlocal EnableDelayedExpansion

C:\...>set output=OutputMSI

C:\...>for %x in (ABC DEF GHI) do (
set products_dir=OutputMSI\%x\products
===>             ^^^^^^^^^    ^^^^^^^^ %output% gets expanded here
 mkdir
 ===>  ^^^^^^^^^ %products_dir% doesn't get expanded here
 robocopy publish\%x\  *.application *.deploy /s
 ===>                ^ or here
 copy Version.txt   
 ===>             ^^^^^^^ or here
)

C:\...>(
set products_dir=OutputMSI\ABC\products
 mkdir
 ===>  ^^^^^^^^^ %products_dir% still not expanded here
 robocopy publish\ABC\  *.application *.deploy /s
 ===>                ^ or here
 copy Version.txt   
 ===>             ^^^^^^^ or here
)
The syntax of the command is incorrect.

变量在set行上展开,但之后不再展开。关于for循环或setlocal

,我错过了什么?

我在没有EnableDelayedExpansion的情况下尝试过,并且我尝试将变量名称周围的%加倍,但两者都没有成功。

1 个答案:

答案 0 :(得分:2)

setlocal EnableDelayedExpansion - 有"启用"在里面。只有准备批处理才能使用延迟扩展。要实际使用延迟变量,请将其括在!而不是%之间:

set var=XYZ
for %%x in (ABC DEF GHI) do (
    set var=%%x
    echo %%x, !var!, %var%
)