Batch File : Read File Names from a Directory and Store in Array
Simulating Array
String is the only variable type in batch file. However, arrays can be simulated with several variables of identical name except a trailing numerical ID such as:
Array[1] Array[2] Array[3] Array[4] etc...
We can store each file name into these variables.
Retrieving command output
The first step is to put the command output into a variable. We may use the for /f
loop.
for /f %%G in ('dir *.txt /b') do set filename=%%~G
The ('')
clause and /f
option specifies to collect the command output. Note that the filename you get is always the last one displayed because of variable-overwriting. This can be resolved by appending instead, but is beyond the scope of this answer.
Giving ID to files
In this case, I will name the array filename
with a trailing ID [n]
, where n
is a numerical ID.
setlocal enableDelayedExpansion
set /a ID=1
for /f "delims=" %%G in ('dir *.txt /b') do (
set filename[!ID!]=%%~G
set /a ID+=1
)
set filename
endlocal
Two things to note:
I have added
"delims="
into the loop to ensure it works properly with default delimiters.I replaced
%ID%
with!ID!
because of delayed expansion. In short, when delayed expansion is disabled, the entire for loop is phrased before runtime, variables with new values are not updated block(()
) structures; if enabled, the said variables are updated.!ID!
indicates the need for update in each loop.
You can give a try for this batch file :
@echo off
Title Populate Array with filenames and show them
set "MasterFolder=%userprofile%\desktop"
Set LogFile=%~dpn0.txt
If exist "%LogFile%" Del "%LogFile%"
REM Iterates throw all text files on %MasterFolder% and its subfolders.
REM And Populate the array with existent files in this folder and its subfolders
echo Please wait a while ... We populate the array with filesNames ...
SetLocal EnableDelayedexpansion
@FOR /f "delims=" %%f IN ('dir /b /s "%MasterFolder%\*.txt"') DO (
set /a "idx+=1"
set "FileName[!idx!]=%%~nxf"
set "FilePath[!idx!]=%%~dpFf"
)
rem Display array elements
for /L %%i in (1,1,%idx%) do (
echo [%%i] "!FileName[%%i]!"
(
echo( [%%i] "!FileName[%%i]!"
echo Path : "!FilePath[%%i]!"
echo ************************************
)>> "%LogFile%"
)
ECHO(
ECHO Total text files(s) : !idx!
TimeOut /T 10 /nobreak>nul
Start "" "%LogFile%"