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 should you want to delete even 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 Equivalent: PowerShell methods - Math operations (.addDays)


 
© BACK 2 Rank aka Tracer
"Lameness is not a reason for suicide but posing with eliteness is a reason for murders"