Batch CMD - delete files by age

We are performing daily full database backup in office. As part of the maintenance effort to keep only the most recent 30 days backup, I was looking for a way to purge old files using cmd batch and I came across this neat script. Schedule this to run on a daily basis and viola, you have yourself an automated purge job running in 5 minutes.

This script is with the assumption that you create a backup file each day. It compiles the directory file listing (in the order of date created) into file.txt, skipping the first 29 entries and delete 30th and onward. Short, simple and it works.

@echo off
setlocal
Dir c:\testing\*.bak /B /O:-D /T:C > c:\temp\file.txt
For /f "skip=29 delims=/" %%a in (c:\temp\file.txt)do del "c:\testing\%%a" /f /q
Endlocal
Exit

Related Links

Delete Files by Age


About this entry