DIR output into BAT array?

arrays, batch-file

Solution

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.

Problem

Is there a way to read in the output of a 'dir' command into an array in a BAT file? Or would I need to output it to a file first, then read the file and delete the file after? The purpose is to get a list of folders in a directory, append a number to each and then prompt the user for a numerical input to select a folder. UPDATE : got it! ``` SETLOCAL EnableDelayedExpansion SET /A c=1 FOR /F "tokens=*" %%F in ('dir /on /b /a:d /p %svnLOCAL%') DO ( ECHO !c!. %%F SET dir_!c!=%%F SET /a c=c+1 ) REM test array ECHO !dir_4! ENDLOCAL ```

Original source

Related problems