setlocal
for /F "tokens=1,2" %%a in (%env_cells%) do (
call :env_setter env_setter_%%a
)
goto:EOF
:env_setter
rem doesn't do anything
endlocal
call %%1
goto:eof
问题是上面禁用了由env_call产生的所有调用中的全局变量设置。有办法解决这个问题吗?
也许这是一个更详细的解释:
env_setter是对批处理文件的调用,该批处理文件本身包含set
个调用,旨在在此调用上下文中设置环境变量。因为在调用!env_cell期间启用了setlocal
!和endlocal in:env_cell似乎没有禁用endlocal,表示set调用不会按预期更改此上下文。
在这个特定的例子中,可以使用%% a但我希望一般地理解这个功能。
是否有手动方式在if / for块中反复访问变量值?
答案 0 :(得分:6)
@echo off &setlocal
echo(
echo this obviously doesn't work
set "Counter="
for /l %%a in (1 1 5) do (
SETLOCAL ENABLEDELAYEDEXPANSION
set "Counter=!Counter!1"
set "Variable=!Variable!!Counter!"
echo !Counter!:!Variable!
endlocal
)
echo Counter's value in the calling environment : %Counter%
echo Variable's value in the calling environment: %Variable%
echo(
echo throw your variables over the wall!
set "Counter="
for /l %%a in (1 1 5) do (
SETLOCAL ENABLEDELAYEDEXPANSION
set "Counter=!Counter!1"
set "Variable=!Variable!!Counter!"
echo !Counter!:!Variable!
for /f %%a in ('set Counter^&set Variable') do (if "!"=="" endlocal)&set "%%a"
)
echo Counter's value in the calling environment : %Counter%
echo Variable's value in the calling environment: %Variable%
答案 1 :(得分:3)
不可能在函数中使用endlocal来保留在函数外部设置的setlocal。
但是当语法错误发生时,所有setlocal实例仍然存在且无法使用endlocal删除,因此可以设置全局变量。
setlocal
for /F "tokens=1,2" %%a in (%env_cells%) do (
call :env_setter env_setter_%%a
)
goto:EOF
:env_setter
set myNewGlobal=1
call :haltAndStore
goto:eof
:haltAndStore
()