Search code examples
for-loopbatch-fileforfiles

Forfiles command in For Loop


Simplified working Script part from a Batch File

for %%F in 
(
C:\A\*.TXT
) do (
echo %%F
)

This prints out all .TXT filepaths from folder A.

I would like to add a forfiles extension in order to only get .TXT files /D -2

for %%F in ('
forfiles /P "C:\A\" /M *.TXT /D -2 /C "cmd /c echo @PATH"
') do 
(
echo %%F
)

But this only prints the forfiles command as string:

'forfiles
/P
"C:\A\"
/M
/D
-2
/C
"cmd /c echo @PATH"'

How do I have to hand over the forfiles command to make this work - if possible at all.


Solution

  • I just tried this and it works fine:

    forfiles /M *.TXT /D -2 /C "cmd /c echo @file"
    

    As you see, you don't need to add forfiles to your for-loop, because it replaces the for-loop.

    In case you want this for all files inside subdirectories, you might add the /S switch:

    forfiles /S /M *.TXT /D -2 /C "cmd /c echo @path"
    

    ... and if you want to specify a directory, you might do this:

    forfiles /P C:\ /S /M *.TXT /D -2 /C "cmd /c echo @path"