Delete Files That Are Older Than X Days in Windows

code

There was a need to delete log files that were older than a certain date from a folder on a Microsoft Windows based computer. This proved to be a difficult task to develop the proper command line that would accomplish this task. However there is a native Microsoft Windows command that does provide the necessary tools to delete files that are older than a certain date among other uses, FORFILES. FORFILES Selects a file (or set of files) and executes a command on that file, which is helpful for batch jobs.

Use the following syntax to use FORFILES.

FORFILES [/P pathname] [/M searchmask] [/S] [/C command] [/D [+ | -] {MM/dd/yyyy | dd}]

From Stackoverflow, I was able to construct this simple command to delete log files that are older than 14 days from within a specific folder.

FORFILES /m *.* /d -14 /c "cmd /c del @path"

Among the many paramaters that FORFILES /? will reveal, the following are used in the above command.

/M searchmask Searches files according to a searchmask. The default searchmask is ‘*’ .

/D date Selects files with a last modified date greater than or equal to (+), or less than or equal to (-), the specified date using the “MM/dd/yyyy” format; or selects files with a last modified date greater than or equal to (+) the current date plus “dd” days, or less than or equal to (-) the current date minus “dd” days. A valid “dd” number of days can be any number in the range of 0 – 32768. “+” is taken as default sign if not specified.

/C command Indicates the command to execute for each file. Command strings should be wrapped in double quotes.

The default command is “cmd /c echo @file”.

The following variables can be used in the command string:
@file – returns the name of the file.
@path – returns the full path of the file.

To include special characters in the command line, use the hexadecimal code for the character in 0xHH format (ex. 0x09 for tab). Internal CMD.exe commands should be preceded with “cmd /c”.