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.