Delete Files Older Than a Number of Days From DOS

With the operating systems available today, using the graphical user interface (GUI) of the operating system has become second-nature for me. It is very easy to copy, move, and delete files through the GUI interface than typing out the commands from a command line.

With all the user interface options in an operating system, there are many times where it can be more efficient to use the command line. In one such case, I wanted to create a simple method of deleting files that were older than seven days from a specified directory. While I could have written an application to do this, I wanted to make it more simple by using a batch file. With an additional executable available with the Windows 2003 SDK, I can easily delete files older than a number of days from DOS.

Deleting Files From DOS Older Than Seven Days

Delete Files Older Than a Number of Days From DOS

There is a small executable called ForeFiles that can easily allow you to get the files in a directory that meet certain time criteria. In my case I want to find all files that were older than 7 days.

To do this, I added the following command to a batch file:

forfiles.exe /p D:\Files /s /m *.* /d -7 /c "cmd /c del @file"

The above line executes the forefiles.exe program with the following parameters:

/pThis parameter specifies the path that contain the files I wish to delete.
/sThis parameter tells the program to recurse into any subfolders to look for other files.
/mIf you want to specify a specific file type, this parameter will allow you to limit the search to specific files, such as *.doc for Word documents. In my case, I looked for all files (*.*).
/dThis one is the key parameter – it specifies the last modified date value. In my example I specify “-7” which indicates that the files need to have a modified date 7 days less than the current date.
/cThis is the command that I execute on the files found by the program. The delete command is executed in a command window for each file.

While there are many ways to perform such an action through other applications, some times I find using batch files, and then scheduling them to run, can be just as easy.

Follow Me