Windows 10

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

In this tutorial, we’ll learn how to delete files older than a specific number of days using a batch script with the FORFILES command. This is especially useful for cleaning up old logs, backups, or temp files automatically.

Batch files contain a series of DOS (Disk Operating System) instructions that help automate system tasks.
 
 

🧾 Syntax of FORFILES:
forfiles /p "C:\path\to\dir" /s /m *.* /D -<number_of_days> /C "cmd /c del /F /Q @path"
Option Description
/p Specifies the path to the directory (default is current folder).
/s Includes subfolders.
/m Specifies file pattern; *.* means all files.
/D -N Targets files older than N days.
/C Executes the command for each file.
@path Refers to the full path of the file.
del /F /Q Deletes files forcibly and quietly (no confirmation).

 
 

📁 Example 1: Delete All Files Older Than 30 Days

The following script deletes all files older than 30 days in the C:\Users\StackHowTo\myFiles directory and its subfolders:

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

📝 Output:
All matching files older than 30 days will be permanently deleted without prompting.


 

📄 Example 2: Delete a Specific File If Older Than 30 Days

The following script deletes the file myfile.txt if it is older than 30 days:

@echo off
forfiles /m myfile.txt /d -30 /C "cmd /c del /F /Q @file"

 

🔁 Additional Notes:
  • To delete files newer than 30 days, use /D +30.
  • You can also use specific date formats:
    • /D -01/01/2024 → delete files modified before January 1, 2024.
    • /D +01/01/2024 → delete files modified after January 1, 2024.
  • To target only the root directory (not subfolders), omit the /s flag.
  • Always test with non-critical files first to avoid accidental deletion.
✅ Ideal Use Cases:
  • Automating cleanup of old log or cache files.
  • Managing disk space by regularly deleting obsolete data.
  • Scheduled via Task Scheduler for daily/weekly cleanups.
🚀 Boost your productivity with the best AI toolsTry them

Leave a Reply

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