this problem has been bothering me for hours. I hope someone could help shed some light. Basically, I am trying to scan through all the files (of a specific type) in a folder (there are no subfolder inside, so no need to worry this case), get those files' name, and concatenate all into one string for example, if a folder has two files, a.xml, b.xml and c.xml, I want to get a string looks like
-a a.xml -a b.xml -a c.xml
Below is my code.
copy *.xml C:\FTP
setLocal Enabledelayedexpansion
set "directory=C:\temp"
set "attachment= "
set "a= -a "
for %%n in (%directory% *.xml) DO (
set "attachment=!attachment! %a% %directory%\%%n "
echo.%attachment%
)
setlocal disabledelayedexpansion
echo.%attachment%
The output is shown in this image https://i.sstatic.net/tiw6p.jpg the problem I have is that first, all echoes in the for loop prints out nothing. as shown in those blank lines. the final string I want,i.e. attachment, contains an initial substring of
-a C:\temp\C:temp.
This is actually not a file. the final string I want should be one that is without this substring, only those behind it. By the way, if there is no file inside the folder, I want the string "attachment" to just an empty string like "". Can anyone help me? Thanks a lot!
Inside your for
loop you show the value of %attachment%
, so that value is NOT updated in each iteration; you must use delayed expansion to do so.
The set of values in for
command is: (%directory% *.xml)
that is, the value C:\temp
and all files with .xml extension, that I assumed is none in current directory. After that, you use this value in %a% %directory%\%%n
expression, so the result is -a C:\temp\C:\temp
. I think there is not a point here.
If you want not the folder value in the list, just don't insert it and use %~NXn
modifier in the for
replaceable parameter.
Below is the correct code:
copy *.xml C:\FTP
setLocal Enabledelayedexpansion
set "directory=C:\temp"
set "attachment= "
set "a= -a "
for %%n in ("%directory%\*.xml") DO (
set "attachment=!attachment! %a% %%~NXn "
echo.!attachment!
)
setlocal disabledelayedexpansion
echo.%attachment%