Windows – Quickest way to scheduled file deletion on Windows

batchdeletingscheduled-taskwindows

I have a windows server machine that takes daily backup daily and each daily backup takes 1.5gb thus every night, I want to remove backup files that are older than 1 week.

This is how my back up files are organised:

backup.20091118.gz.gpg , as you can see 20091118 part is the one identifies the file date which is 2009/11/18 (year,month,day) .

I am planning to write a quick batch script for this and schedule it via task manager, is this a good idea? If so I would be greatful for assistance at the batch script part.

Best Regards

Best Answer

Instead of worrying about the age of the files, first delete old backups until there are only 7 daily backups remaining and then worry about deleting the oldest file in the directory before we do each new backup.

Deleting the oldest file in a directory is pretty easy to do in batch script:

SET BACKUPDIR=C:\PATH\TO\BACKUPS
FOR /F %%i IN ('DIR /B /O-D %BACKUPDIR%') DO SET OLDEST=%%i
DEL %BACKUPDIR%\%OLDEST%

The only real trick is the command DIR /B /O-D which lists plain file names sorted by date, oldest last. We use the FOR loop to capture each file name in the OLDEST variable so when the loop is done %OLDEST% will expand to the name of the oldest file.