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 withset _filelist=%_filelist:,,=%
removing the double comma prefixed value.Script
Further Resources