Windows – Set Global Variable in Subroutine with IF in Windows Batch

batchwindows

i have the following Problem with the way the cmd Interpreter works with Variables.
I canĀ“t get it working.
Can you tell me the trick ?

Problem: I call a Subroutine with an Argument in Batch-File.
Depent on what Value the Argument is, the Subroutine dynamicaly builds a String in a Variable. That Variable should be used in the Main-Batch.

@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

Output of this Sript executed Twice:

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

I expected the following output, but how ??

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

Can you help me ?
regards
morlogg

Best Answer

Use delayed expansion, i.e. put

setlocal enabledelayedexpansion

at the start of your batch and then use

FOR %%U IN (%globalvar%) DO (
  call :SUBROUTINE %%U
  echo Variable DYNAMIC after Subroutine: !dynamic!
)

%dynamic% is expanded the instant cmd parses the complete for loop; therefore it cannot pick up a value you set in the subroutine (which obviously happens inside the loop).

Related Question