Daily IT Matters, this is the place where I post my daily findings on IT.

Monday, November 02, 2009

Delete files older than x days using batch script

This one keeps coming back when you are administering several systems which are all pushing out some files to storage for example OLD SQL servers who are spitting out BAK files.

Forfiles /P D:\SQLbackup /S /M *.BAK /D -2 /C "cmd /c del /q @path"

Forfiles is standard included in windows since Windows 2000

Let me explain the switches I used.

/P |This one is for specifying the path.
/S |This is the same as in the dir command for recursively enumerating the files.
/M |Where you specify the search pattern to look for.
/D -2 |This is the most interesting part beacause this switch looks for files older or equal than 2 days.
/C |Here is where you specify what to do. If you want to start a command make sure it starts with cmd /c, I did a del command specifying the file by using the @path variable.