Tuesday, December 4, 2012

Delete files / folders older than X days on windows (bat file)

This script will delete all MS SQL database backups (*.bak files) older than 30 days on the current directory and all its subdirectories:

forfiles /s /m *.bak /d -30 /c "cmd /c del @path"


This script will delete all MS SQL database backups (*.bak files) older than 30 days on a specified directory and all its subdirectories:

forfiles /p "c:\database\backups" /s /m *.bak /d -30 /c "cmd /c del @path"



This script will delete all folders older than 30 days on a specified directory:


forfiles /p "C:\todelete" /m * /d -30 /c "cmd /c rd /s /q @path"  


More from here: ForFiles

If you don't have the forfiles.exe, you can download it from here: ForFiles.zip