Windows – Concatenate all filenames inside a folder in a variable within a Batch script

batchcommand linewindows

I'm trying to create a file list to pass to a program as an argument but i'm having problems with it.

My desired output should be: file1.jpg, file2.bmp, file3.docx

The bat i'm trying to use is this:

SETLOCAL EnableDelayedExpansion
cd /D %~dp0
set _filelist=
for /f "delims=|" %%f in ('dir /b %CD%') do (
  set "_filelist=%_filelist%,%%f"
)
echo %_filelist%
pause

But it only output the last file in the list: ,lastfile.xyz

What i'm doing wrong?

Best Answer

It seems like you simply forgot to use the exclamation mark ("!") with the variable you set within the loop, and to resolve to simply use !_filelist! rather than %_filelist%.

The below script will set the initial set _filelist=, variable with a single comma value so the first iteration will be ,, and then the first iterated value rather than the null plus one comma you get two back to back commas giving a unique pattern to work with for parsing.

You can use Variable Replace functionality to parse out the double commas (,,), and replace those with a blank value. The final iterated and set variable value will then be parsed from outside the loop with set _filelist=%_filelist:,,=% removing the double comma prefixed value.

Script

SETLOCAL EnableDelayedExpansion
cd /D %~dp0
set _filelist=,
for /f "delims=|" %%f in ('dir /b %CD%') do (
  set "_filelist=!_filelist!,%%f"
)
set _filelist=%_filelist:,,=%
echo %_filelist%
pause

Delayed Expansion will cause variables within a batch file to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL EnableDelayedExpansion command. [1]


When delayed expansion is in effect, variables can be immediately read using !variable_name! you can also still read and use %variable_name% that will show the initial value (expanded at the beginning of the line). [1]


Further Resources

Related Question