A simple batch script to delete Folders older than x

I had a very simple task I wanted automated:

Delete all folders in a directory older than 4 days.

As it was a simple task I was looking for an EQUALLY simple solution to run via a batch script in Windows, and was surprised how many different approaches, comments, solutions and semi-solutions are out there.  And man, just google around and see how many people were writing complicated or infinitely configurable solutions.  Great for them, but really I just want to trash these old folders.

So, even though I could, I didn’t want to install any third party tools (no matter how “COOL”), write a C# program, delve into VBScript – as all this was way more complicated than this job needed.  Basically just wanted to create a one or 2 line .bat file that would delete the folders without any elaborate conditionals on empty folders, file extension filtering…  just a single damn hard coded “nuke the old folders” script.

What I found was that a DOS script really doesn’t seem to provide easy ways to do conditionals around timestamps.  There are a lot of resources on the web where people are attempting to achieve this, and I spent way too much time tracking their progress across multiple threads and blogs.

So I hunkered down and just wrote something with forfiles.  It’s is available on my Windows 2007 server, and was able to handle the nuking in a very simple one line statement.

ForFiles /P C:backups  /D -4 /C “CMD /C if @ISDIR==TRUE echo RD /Q @FILE &RD /Q /S @FILE”

I saved this into a batch file deleteOldBackups.bat and scheduled as a daily system task.

Some notes:

  • you can change the path: /P C:backups
  • set the date interval (here it’s set to delete anything more than 4 days old) : /D -4  
  • Forfiles date functions appear to work off the modified date rather than the created date, but this works fine for me as the nightly batch script that copies folder into C:backups always sets the modified dates for those folders to the date that it was copied.

There are a lot of switches and parameters that you can use to apply conditional logic to. Check out msdn here, http://technet.microsoft.com/en-us/library/cc753551(WS.10).aspx