1 min read

Delete files older than X days

Delete files older than X days
Photo by Ilya Pavlov / Unsplash

The following instructions wil show a way to get rid of older files.
We will use a standard tool within Windows "Forefiles" to search and delete files older than 7 days

⚠️
Before running the command, please read the documentation from Microsoft here
Forfiles /P "<FodelderPath>" /S /D -7 /C "cmd /c del /s @file"

Within the Forfiles command there are some parameters defined to tell Forefiles what to do with it.

  • /P Is for the path
  • /S Will tell Forefiles to also look in subfolders
  • /D Total days to look
  • /C Command that passes through the Forefiles information gathered from the output.

After the /C parameter there is another command that tells what to do with the Files found in Forefiles, in this code it will delete all files within the Forefiles output.
The @File is a variable from Forefiles that passes through the files to the del command.

After defining the Path and running the command it wil show you which files are being deleted.


Powershell

There's also a Powershell command for this operation.

Get-ChildItem –Path "<Source>" –Recurse | Where-Object { $_.CreationTime –lt (Get-Date).AddDays(-7) } | Remove-Item