Deleting Files Older Than a Certain Number of Days

If you’ve been following my series of posts on scheduling automatic backups to the cloud, you’ll have read how it’s possible to select just the daily, changed files for backup. It occurred to me when setting this up that what I also needed to be able to do is delete files older than a certain age from the backup folder.

Why delete files?

Well for me, my main backup location is my external hard drive. As a secondary backup, I backup all important daily business files to my cloud storage until a client job is satisfactorily completed, then I can delete them from this secondary storage. Another reason for deleting files is when a business client specifies that I delete them a certain number of days after job completion. Finally, most cloud storage providers only give you a limited amount of free storage, so it’s useful to be able to delete files older than a certain age to prevent going over the free quota.

Batch file to delete old files

A quick Google search revealed that Windows includes a program called forfiles which will do this job – I had no idea about this! Here’s the basic line you’ll need to add to your backup batch file:

forfiles.exe /p “C:\<directory with files>” /s /m *.* /d -<number of days> /c “cmd /c del @file”

Looks daunting, but it’s just the program name followed by a number of parameters. What follows /p is the path to the files to delete; /s tells the program to delete from subfolders as well; what follows /m specifies the file types to delete; what follows /d is the key parameter here and selects files with a last modified date earlier than or equal to (-) the current date minus the number of days specified, e.g. /d –45 would delete files older than 45 days; what follows /c runs the specified command on the path specified earlier. Command strings are enclosed in quotation marks.

I’ve added this to my scheduled batch file given in the earlier post so it now backs up encrypted daily files and also deletes all files older than 45 days. These changes are then synced to my cloud storage.

Finally, a word of warning. Deleting files is dangerous, especially when you are setting up scheduled automated deletion. Be sure to back up all you data before testing and implementing this routine.

One Response

  1. Vinod Says:

    Excellent article. Keep it up

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment. Please do not use keywords in the Name field. Comments must relate to the post topic. This website is here to help people, not for advertising purposes.

Please complete puzzle and then submit your comment *
Time limit is exhausted. Please reload CAPTCHA.

` `