Shevek
Shevek

Reputation: 4053

Batch file with nested loops and EnableDelayedExpansion

I am trying to write a batch file to perform an action across multiple servers in multiple environments.

After following the answer here I have managed to be able to loop through the environments but am stuck then looping through the servers in those environments.

Given the following script:

@echo off
set Environments=DEV01,DEV02,TST01,TST02,UAT01,UAT02

set SERVER_DEV01=DEV01SERVER01
set SERVER_DEV02=DEV02SERVER01
set SERVER_TST01=TST01SERVER01
set SERVER_TST02=TST02SERVER01
set SERVER_UAT01=UAT01SERVER01,UAT01SERVER02
set SERVER_UAT02=UAT02SERVER01,UAT02SERVER02

setlocal EnableDelayedExpansion 
(
    for /d %%e in (%Environments%) do (

        set servers=SERVER_%%e

        for /d %%s in (!servers!) do (
            echo !%%s!
        )
    )
)
endlocal

I am expecting the output to be:

DEV01SERVER01
DEV02SERVER01
TST01SERVER01
TST02SERVER01
UAT01SERVER01
UAT01SERVER02
UAT02SERVER01
UAT02SERVER02

But am getting:

DEV01SERVER01
DEV02SERVER01
TST01SERVER01
TST02SERVER01
UAT01SERVER01,UAT01SERVER02
UAT02SERVER01,UAT02SERVER02

How can I get my desired output?

Upvotes: 0

Views: 426

Answers (1)

PA.
PA.

Reputation: 29339

you will need to parse the value of the variable one level down. try

    for %%n in (!servers!) do (
        for %%s in (!%%n!) do (
           echo %%s
        )
    )

Upvotes: 2

Related Questions