3

I am having issues making this syntax work correctly. What I would like to do is remove all tmp and bak files from the specified directory and all subdirectories if the modified date is older than 7 days.

for %G in (.tmp, .bak) do forfiles -p "C:\test\cad projects" -s -m *%G -d -7 -c "cmd /c del @path"

My syntax was gathered from this StackOverflow question.

If I change my search mask to only include one desired extension then I get correct results.

forfiles -p "c:\test\cad projects" -s -m *.bak -d -7 -c "cmd /c del @path"

I don't do much with batch files so I was hoping someone could assist. Thanks for reading.

TWood
  • 317

2 Answers2

5

If you're running this from the console, it should work. If you're saving this to a .bat file, then the format for variables is a little different. You have to use two percentage signs to signify a variable. So, your command would then become...

for %%G in (.tmp, .bak) do forfiles -p "C:\test\cad projects" -s -m *%%G -d -7 -c "cmd /c del @path"

Microsoft's KB75634 article explains why this is.

If there are no characters between the two percent signs, one percent sign is stripped off and the other will remain. This is why a FOR command that echos the name of each file with a .COM extension would be

FOR %V IN (*.COM) DO ECHO %V

but if the same command is placed in a batch file, the following is required:

FOR %%V IN (*.COM) DO ECHO %%V
Drew Chapin
  • 6,020
0

Well I didn't read carefully enough on the FOR /R syntax. I was missing a %. My code above would have worked at the command line. From a batch though, it failed because of the missing %.

for %%G in (.tmp, .bak) do forfiles -p "C:\test\cad projects" -s -m
*%%G -d -7 -c "cmd /c del @path"
TWood
  • 317