How to loop through array in batch?

I created an array like this:

set sources[0]="\\sources\folder1\"
set sources[1]="\\sources\folder2\"
set sources[2]="\\sources\folder3\"
set sources[3]="\\sources\folder4\"

Now I want to iterate through this array:

for %%s in (%sources%) do echo %%s

It doesn't work! It seems that script is not going into the loop. Why is that? How can I iterate then?


Solution 1:

Another Alternative using defined and a loop that doesn't require delayed expansion:

set Arr[0]=apple
set Arr[1]=banana
set Arr[2]=cherry
set Arr[3]=donut

set "x=0"

:SymLoop
if defined Arr[%x%] (
    call echo %%Arr[%x%]%%
    set /a "x+=1"
    GOTO :SymLoop
)

Be sure you use "call echo" as echo won't work unless you have delayedexpansion and use ! instead of %%

Solution 2:

If you don't know how many elements the array have (that seems is the case), you may use this method:

for /F "tokens=2 delims==" %%s in ('set sources[') do echo %%s

Note that the elements will be processed in alphabetical order, that is, if you have more than 9 (or 99, etc) elements, the index must have left zero(s) in elements 1..9 (or 1..99, etc.)

Solution 3:

If you don't need environment variables, do:

for %%s in ("\\sources\folder1\" "\\sources\folder2\" "\\sources\folder3\" "\\sources\folder4\") do echo %%s