How-to: Delete files older than N days

There are several ways to do this

1) Using ForFiles to delete files over 7 days old:

C:\> forfiles /p "C:\source_folder" /s /m *.* /c "cmd /c Del @path" /d -7

2) Using Robocopy /Move to delete files over 7 days old:

C:\> set _robodel=%TEMP%\~robodel
C:\> MD %_robodel%
C:\> ROBOCOPY "C:\source_folder" %_robodel% /move /minage:7
C:\> del %_robodel% /q

3) Using DateMath.cmd and Getdate.cmd, download DelOlder.cmd

4) With PowerShell delete files over 7 days old:
PS C:\> $now = get-date
PS C:\> dir "C:\source_folder\" | where {$_.LastWriteTime -le $now.AddDays(-7)} | del -whatif

PowerShell also has .AddHours if you want to delete more recent files.

“We were having one of those great first dates you can only have when it's not an actual date” - Sarah Jessica Parker

Related commands:

SetLocal - Control the visibility of environment variables in a batch file.
PowerShell methods - Math operations (.addDays)

Copyright © 1999-2021
Some rights reserved