Windows 10

Batch File To Delete Folders Older Than N Days

In this tutorial, we are going to see how to delete folders 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 /D -<number of days> /C "cmd /c IF @isdir == TRUE rd /S /Q @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.

 

 

Batch File To Delete Folders Older Than N Days

The following example deletes all folders from “C:\Users\StackHowTo\myFolders” 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:


 

Leave a Reply

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