Your second part is wrong. Since there are no real arrays in batch scripting, you cannot use a for
loop similar to something like for each element in array do
as used in other languages. Refer to this post for details: Arrays, linked lists and other data structures in cmd.exe (batch) script.
To loop through all (pseudo-)array elements you could do the following instead:
set /A count=integer-1
for /L %%i in (0,1,%count%) do echo Paths[%%i] = !Paths[%%i]!
As suggested by Aacini in a comment, you might change your base-0 to a base-1 (pseudo-)array by moving the line set /A integer+=1
upwards to be before line set Paths[!integer!]=%%a
in your first part, so the variable integer
already contains the greatest index, which would lead to a slightly simpler second part:
for /L %%i in (1,1,%integer%) do echo Paths[%%i] = !Paths[%%i]!
Alternatively, you could use a for /F
loop that parses the output of set Paths[
:
for /F "tokens=1* delims==" %%i in ('set Paths[ 2^> nul') do echo %%i = %%j
This might be beneficial:
- you do not need to know the total number of elements;
- the indexes do not have to be adjacent, they could even be non-numeric;
But there are two caveats:
- the (pseudo-)array elements are not returned in ascending order with respect to the indexes, because
set Paths[
returns them alphabetically sorted, where the order is 0
, 1
, 10
, 11
,..., 2
, etc., so the order becomes jumbled as soon as there are indexes with more than a single digit;
- in case there exist other variables beginning with that name, like
Paths[invalid]
or Paths[none
, they become returned too;