How to loop over environment variables in windows batch file? [duplicate]

旧时模样 提交于 2020-12-26 09:24:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!