我对 cmd 解释器处理变量的方式有以下问题。我无法让它工作。你能告诉我诀窍吗?
问题:我在批处理文件中使用参数调用子程序。根据参数的值,子程序会动态地在变量中构建一个字符串。该变量应该在主批处理中使用。
@echo off
set globalvar=text_two,text_one
FOR %%U IN (%globalvar%) DO (
call :SUBROUTINE %%U
echo Variable DYNAMIC after Subroutine: %dynamic%
)
goto :END
:SUBROUTINE
::This Subroutine should Build the VARIABLE depended on the Argument
echo Dynamic in SUB1: %1
IF /I %1==text_one (set dynamic=dynamic_text_example_one)
IF /I %1==text_two (set dynamic=dynamic_text_example_two)
goto:EOF
:END
该脚本执行两次后的输出:
Dynamic in SUB1: text_two
Variable DYNAMIC after Subroutine:
Dynamic in SUB1: text_one
Variable DYNAMIC after Subroutine:
Dynamic in SUB1: text_two
Variable DYNAMIC after Subroutine: dynamic_text_example_one
Dynamic in SUB1: text_one
Variable DYNAMIC after Subroutine: dynamic_text_example_one
我期望得到以下输出,但是如何呢?
Dynamic in SUB1: text_two
Variable DYNAMIC after Subroutine: dynamic_text_example_two
Dynamic in SUB1: text_one
Variable DYNAMIC after Subroutine: dynamic_text_example_one
Dynamic in SUB1: text_two
Variable DYNAMIC after Subroutine: dynamic_text_example_two
Dynamic in SUB1: text_one
Variable DYNAMIC after Subroutine: dynamic_text_example_one
你能帮助我吗?问候 morlogg
答案1
使用延迟扩展,即
setlocal enabledelayedexpansion
在批处理的开始处,然后使用
FOR %%U IN (%globalvar%) DO (
call :SUBROUTINE %%U
echo Variable DYNAMIC after Subroutine: !dynamic!
)
%dynamic%
瞬间扩大cmd
解析完整的for
循环;因此它无法获取你在子程序中设置的值(这显然会发生里面循环)。