Batch Command To Delete Old Files Using Forfiles.exe
2009-05-05 Initial Post
You can use the Forfiles command to search for files with certain parameters and then execute commands against the results. This is useful for automated cleanup of backup and log files.
Here’s a sample batch file to delete files that haven’t been modified in 3 days. You can schedule this batch file with Windows Tasks. Note that UNC paths are not supported, but you can map a drive, run the command, and then delete the drive mapping, as shown below.
IMPORTANT NOTE: Make sure you have the command to delete the existing drive mapping before you map a new drive. This is a precaution in case you have a drive mapped and for some reason the batch file doesn’t overwrite the existing mapping properly. This actually happened to me, but luckily I caught the error and canceled the batch file in time.
[batch]
REM Deletes files older than 3 days from mapped drive path
net use Z: /delete
net use Z: \\server-1\Backups\SystemState
Forfiles /P Z:\ /D -3 /C "cmd /c DEL /Q @path"
net use Z: /delete
[/batch]
If I ran the command on 05-05-2009 with the “/D -3” option, this instructs Forfiles to delete all files with modified dates equal to or older than the current date minus 3 days. That would equal 05-05-2009 minus 3 days, so any file with a modified date equal to or older than 05-02-2009 would get deleted.
See http://technet.microsoft.com/en-us/library/cc753551.aspx for more info. I checked a few Windows Server 2003 R2 systems and they all have forfiles.exe in C:\WINDOWS\system32\. I didn’t see forfiles.exe on XP Pro SP3, but the file can be copied over from a server and used on XP.