Delete files over 30 days old

You can delete files older than a specific age using the forfiles command. This command first became available with Windows Server 2003 and Windows Vista. If you are on Windows XP, you can copy the forfiles.exe command from a 2003 server and run it since they share the same code base.

The -p parameter provides the directory you want to delete from and -s tells it to include sub-directories. The -m parameter provides the file mask to delete, so *.* deletes all files and *.log only deletes files with the .log file extension. The /D-30 parameter tells it to delete files more than 30 days old. You can change the 30 a different number of days, such as /D-180 would only delete files over 180 days old. The /C parameter tells it to run the following command in quotes. Use del to tell it to delete and @path picks up the directory you listed in the -p parameter.

Here is an example batch file that will delete files older than 30 days in a temp directory off the root of C.

@echo off
forfiles -p "C:\temp\" -s -m *.* /D-30 /C "cmd /c del @path"

This example deletes IIS log files greater than 30 days old.
@echo off
forfiles -p "C:\inetpub\logs\LogFiles\W3SVC1\" -s -m *.log /D-30 /C "cmd /c del @path"

Comments are closed.