Tuesday, August 04, 2009

JJClements.co.uk » Delete files older than certain number of days

 

I was recently asked to investigate a problem with a server and the lack of space on a partition. After a quick look using Treesize I noticed a suspicious folder being used by an application for logging purposes.

There were over 700,000 files in it! When I tried to browse the folder using explorer it took an absolute age to open as you can imagine. To rectify the problem and recover the majority of the disk space being used by the logs I wanted to delete the contents of the logging folder that was older than 30 days. After a quick search I discovered a command line utility called forfiles.exe that is included with Windows Server 2003. Using forfiles.exe I was able to delete all files older than 30 days like so:

forfiles.exe /p (pathtofilestodelete) /s /m *.* /d -30 /c "cmd /c del /q @path"

A working example is:

forfiles.exe /p d:\logs /s /m *.* /d -30 /c "cmd /c del /q @path"

This will delete ALL files from d:\logs (and all sub folders it contains because /s has been used to force recursion) older than 30 days without prompting you to confirm deletion.

Here is an explanation of the switches I used:

/p = The path to search for the files you want to check the date of and remove
/s = Recurse subdirectories contained within the path specified using /p and check them as well
/m = The search mask to be used for the file type you want to check the date on (*.* being all files)
/d = The date to compare the files against. A standard date type can also be used (dd/mm/yyyy)
/c = The command to be used on a file that matches the /m and /d criteria
/q = Used within /c to instruct the del command to delete files quietly

JJClements.co.uk » Delete files older than certain number of days

No comments: