Search code examples
for-loopbatch-file

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

  • 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.)