I recently had to find out a way to cleanup files in a folder that was growing based upon the date that they were originally created. These log files needed to be kept for 3-4 months in case they need to be reviewed for verification. Unfortunately there was a huge amount of files in the folder and not all needed to be cleared out. One folder had files ranging in size from 1KB to 64KB that I could see. It took 5-10 minutes to just load up the page in Windows through the GUI. I then dropped out to the command line and did a directory list dump to a test folder. The text file was just over 20MB in size with the file names of all the files in that 5.6GB folder. After some searching and testing I was able to find the command following which I used:
FORFILES (It is natively in newer versions of Windows Vista + and Server 2003+, Server 2000 has a slightly different version through the Resource Kit Tools).
I started my testing by running the following command:
forfiles /P “FullPath” /M File*.xml /D -120 /C “cmd /c echo @path @fdate” > C:test.txt
This command did the following:
/P Pathname Path to the folders I needed to check
/M searchmask Searching for list of files that meet these settings like logs*.log or files*.xml
/S Subdirectories Allows search of any subdirectories with the same specifications. I didn’t have any in this test so didn’t use this as a setting
/D date Selects files modified within the range. In my instance it is anything older than 120 days from the date it is run.
/C Command Executes a command to run for each file found. These need to be in Double Quotes to run properly. The ones I chose to check were state [echo] full path of the file [@path – used in case I need to add subdirectories in the future] and the date the file was last modified [@fdate]
> Redirect to Used to redirect output from the screen to someplace else, in this case a file called test.txt located on the root of C.
Once I verified that the file didn’t contain any files newer than the range we wanted to keep and that it didn’t contain any files that were not the log files we were wanting to remove I switched a few settings:
forfiles /P “FullPath” /M File*.xml /D -120 /C “cmd /c del @path”
I tested it to verify that it removed the older files and then I saved it as a batch file and set it up to run as a scheduled task once a week.