Delete files or folders older than x days

There are programs that don’t do a very good job at cleaning up after themselves. Either they create log files that are not pruned, or dump files, the following command can be used to delete old files that are no longer needed.

There are only two things you need to specify: the path, and the number of days – files that are older than this number will be deleted.

This can be a one-time thing, or can be configured as a scheduled task.

For example, if I wanted to delete all files in the E:\Downloads (and all sub-folders) that are older than 30 days, I would run the following command:

cd /d e:
forfiles /S /P "E:\Downloads" /M "*" /D -30 /C "cmd /c del @path"

The same forfiles command can be used to delete folders – see example below.

cd /d e:
forfiles /S /P "E:\Downloads" /D -30 /C "cmd /C IF @isdir == TRUE rd /S /Q @path"

If the the command returns an error check the path, syntax, and the double-quotes. Remove and re-add the double quotes as this is a known issue when certain text is copied/pasted.

Here’s a brief explanation of the parameters used in my examples:

C = command to execute

D = number of days since last modified

@isdir = identifies the object as a directory; can be set to TRUE or FALSE

M = file or folder mask

P = path

Q = quiet

S = recursive, parse all sub-directories