Tuesday 6 February 2018

using FORFILES in batch to delete tmp and bak files older than a week


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.



Answer



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

No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...