Windows 10

Batch File To Delete All Files in Folder Older Than N Days

In this tutorial, we are going to see how to delete all files in a folder older than N days in a batch file by using FORFILES command, which allows you to execute a command on each file selected. Batch file contains a series of DOS (Disk Operating System) instructions. It allows triggering the execution of commands found in this file.
 

 

Syntax:
forfiles /p "C:\path\to\dir" /s /m *.* /D -<number of days> /C "cmd /c del @path"
  • /p “C:\path\to\dir” is the the path to the directory where files to delete exists (default=current folder)
  • /s means include sub-folders
  • /m select files matching the specified wildcard, *.* means all file regardless of the file extension
  • /D specify a date
  • /C specify the command to execute for each file, in this case we have specified “cmd /c del @path”
  • @path is the full path, including name. This will done automatically.

Note that if you want to delete files OLDER than 30 days, you need to specify /D “-30”. And if you want to delete files NEWER than 30 days, you need to specify /D “+30”. You can also specify DDMMYY or -DDMMYY format as the parameter to /D. Example: /D -01/01/2020.

To avoid “Are you sure” messages use del /F /Q @path
 

 

Example 1: Batch File To Delete All Files in Folder Older Than 30 Days

In the following example, we have deleted all files in the folder “C:\Users\StackHowTo\myFiles” older than 30 days.

@echo off

forfiles /p "C:\Users\StackHowTo\myFiles" /s /m *.* /D -30 /C "cmd /c del @path"

Output:


 

Example 2: Batch File To Delete A Specific File Older Than 30 Days

In the following example, we have deleted the file “myfile.txt” if it is older than 30 days.

@echo off

forfiles /m myfile.txt /c "cmd /c Del myfile.txt " /d -30

 

Leave a Reply

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