Windows 10

Batch File To Delete Folders Older Than N Days

In this tutorial, we’ll learn how to delete folders older than a specific number of days using the FORFILES command in a batch script. This is particularly useful for automating cleanup tasks on your Windows system or server.

A batch file contains a series of DOS (Disk Operating System) instructions that automate routine tasks.
 
 

🧾 Syntax of FORFILES:
forfiles /p "C:\path\to\dir" /s /D - /C "cmd /c IF @isdir==TRUE rd /S /Q @path"
Option Description
/p Specifies the path to the directory (default is current folder).
/s Includes subfolders.
/D -N Selects folders with a last modified date older than N days.
/C Executes the given command.
@isdir Checks whether the item is a folder.
rd /S /Q Deletes the folder and all its contents quietly (no prompt).

 
 

🧪 Example: Batch File to Delete Folders Older Than 30 Days

The following batch script will delete all folders in C:\Users\StackHowTo\myFiles that are older than 30 days:

@echo off
FORFILES /p "C:\Users\StackHowTo\myFiles" /S /D -30 /C "cmd /c IF @isdir==TRUE rd /S /Q @path"

📤 Output:
This command will not print output unless a folder fails to delete, but in practice, it will silently remove all matching folders older than 30 days.


 

⚠️ Important Notes:
  • Test carefully before using this in a production environment.
  • This script only removes folders, not individual files.
  • Ensure that the folders are not in use or locked, or the command may silently fail.
  • If you only want to target folders in the root (not subdirectories), remove the /S flag.
✅ Example Use Cases:
  • Cleaning up old log folders.
  • Maintaining backup directories.
  • Automating temp folder cleanups.
🚀 Boost your productivity with the best AI toolsTry them

Leave a Reply

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