Delete old files with Forfiles.exe

Delete old files with Forfiles.exe

cmdRecently I was asked to write a script or method to delete old PDF files from a few scanner folders. The client wanted files old then 30 days to be deleted since people would forget to remove them when they were done and things got cluttered. After doing a little bit of Googling, I found forfiles. An excellent tool built directly into Windows. The online help documentation is available here.

@echo off
forfiles /P “E:\Users Shared Folders\CopierScan” /M *.pdf /D -30 /C “cmd /c del /F /Q /S @file”

This will remove any PDF files in the CopierScan folder and it’s sub directories that are the current day minus 30 days. /C passes a command to each file that forfiles returns. In this case I specify delete with the /F (forces deletion), /Q (quiet), and /S (include sub-folders) flags.

I wrote and tested this script on my Windows 7 computer but when I moved it to the server running Windows Server 2003, it flagged errors in the batch file. I messed around with it for a bit but didn’t really change anything and it started working. It might have been a capitalization thing but I couldn’t say for sure.

My script was relatively simple but you could easily adjust the script for logging dates, times, and what files are being removed. This could be very helpful for removing old logs or backups.

One thought on “Delete old files with Forfiles.exe

Leave a Reply

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