Batch file to delete files older than x days from folders in Windows

I’ve been working for a client over recent months and part of my resposibility has been to look after a number of servers used for performance testing. Occasionally drives fill up on the server farm causing outages and obvious interruptions to testing.

It would be a near full-time job to manage all these servers, so to reduce the chance of temporary files from filling up drives and causing problems, I looked into creating a scheduled task to delete old temporary files. Since my server estate is varied, I didnt want to use PowerShell so I opted for an old “DOS” command, FORFILES.

This seems to have done the trick for me:
forfiles /s /m *.* /d -7 /c "cmd /c del @path"

(This command deletes all files that are more than 7 days old from the folder in which it runs.)

Update – To remove folders as well:
forfiles /S /D -7 /C "cmd /c IF @isdir == TRUE RMDIR @path /S /Q"

(This command deletes all folders that are more than 7 days old from the folder in which it runs. – Run it after deleting the files with the command above.)

 

Author: Richard Bishop

http://about.me/richard_bishop

2 thoughts on “Batch file to delete files older than x days from folders in Windows”

  1. Hello there.
    I’m looking for some way to “delete all files and folders older than….” in Windows 10.
    You have kindly provided the above scripts, but unfortunately they mean absolutely nothing to most people, myself included, who find this in a Google search.
    Would it be too much trouble to explain exactly how to use these scripts?
    Thank-you for your time.

    1. Hi,
      I can see how this may look a bit daunting at first, but this is just an old-fashioned “DOS” command.

      Here’s an easy way to run it:
      Click the Windows icon in the bottom left corner of your screen and type “cmd”
      Before pressing enter you should see a program called “Command prompt” in your search results.
      Click “Command prompt” and you’ll see a screen with a flashing cursor.
      Change directory to any folder where you want to delete files and paste in one of the above commands.

      All the best,
      Richard

Leave a Reply

Your email address will not be published. Required fields are marked *