DIR output into BAT array?

Batch does not formally support arrays, but you can emulate arrays using environment variables.

@echo off
setlocal enableDelayedExpansion

::build "array" of folders
set folderCnt=0
for /f "eol=: delims=" %%F in ('dir /b /ad *') do (
  set /a folderCnt+=1
  set "folder!folderCnt!=%%F"
)

::print menu
for /l %%N in (1 1 %folderCnt%) do echo %%N - !folder%%N!
echo(

:get selection
set selection=
set /p "selection=Enter a folder number: "
echo you picked %selection% - !folder%selection%!

In the code above, the “array” elements are named folder1, folder2, folder3…

Some people use names like folder[1], folder[2], folder[3]… instead. It certainly looks more array like, but that is precisely why I don’t do that. People that don’t know much about batch see variables like that and assume batch properly supports arrays.

The solution above will not work properly if any of the folder names contain the ! character – the folder name will be corrupted during expansion of the %%F variable because of delayed expansion. There is a work-around involving toggling the delayed expansion on and off, but it is not worth getting into unless it is needed.

Leave a Comment