问题
In windows, I want to loop over a set of environment variables like in this pseudo code:
set MYVAR1=test
set MYVAR2=4711
set MYVAR3="a b c"
for /l %%x in (1, 1, 3) do (
echo %MYVAR%s%%
)
for which I expect the following output
test
4711
a b c
How to change this example code to get it to work?
回答1:
@echo off
set MYVAR1=test
set MYVAR2=4711
set MYVAR3="a b c"
setlocal enableDelayedExpansion
for /l %%x in (1, 1, 3) do (
echo !MYVAR%%x!
)
endlocal
回答2:
One more way, parse the output of set
command using the variable prefix
@echo off
setlocal enableextensions disabledelayedexpansion
set MYVAR1=test
set MYVAR2=4711
set MYVAR3="a b c"
for /f "tokens=1,* delims==" %%a in ('set MYVAR') do echo %%b
回答3:
Another method:
@echo off
set MYVAR1=test
set MYVAR2=4711
set MYVAR3="a b c"
for /l %%x in (1, 1, 3) do (
call echo %%MYVAR%%x%%
)
pause
来源:https://stackoverflow.com/questions/24909055/how-to-loop-over-environment-variables-in-windows-batch-file