Search code examples
variablesbatch-filedelayedvariableexpansion

Batch: variable definition useable in count loop


In my batch I want to copy a variable amount of source- to target destinations.

I want to define like this:

@setlocal EnableDelayedExpansion

set source1="C:\folder1"
set target1="f:\folder1"

set source2="C:\folder2" 
set target2="f:\folder2"  
...

set sourcen="C:\foldern" 
set targetn="f:\foldern"

Dependently from a defined amount of folders

set numFolder=5

I want to go through the folders in a loop:

set /a COUNT=0

:LOOP
echo %COUNT%
set /a COUNT+=1

rem write the NAME of the parameter variable (source1,source2 etc.) in nameor 
set "nameor=source%COUNT%"
rem write the VALUE of the parameter variable (source1,source2 etc.) into origin ("C:\folder1", "C:\folder2")
set "origin=%nameor%"
echo %origin%

if %COUNT% lss %numFolder% goto LOOP

When I show

echo %nameor%

I get what I expectet: source1, source2 etc. but

echo %%%origin%%%

only provides

source1

instead of the expected value

"C:\folder1"

I thought, that I could resolve this by using DelayedExpansion but what did I miss?


Solution

  • To avoid confusion for me, I change the "origin" to "source". E.g. set "origin=%nameor%" changed to set "source=%nameor%".

    To print out "C:\folder1" to "C:\foldern", you should use echo !%source%!, else you will just see "source1" to "sourcen".