Site icon SumTips

Delete Files Older Than X Days in Windows with PowerShell & CMD

Windows File Explorer does not have an option to delete files based on their age. So if you wanted to automatically delete old backup files or log files then you’d have to do it manually or by using a third-party tool. However, if you want a command-line solution, then here are two methods for Windows PowerShell and Command Prompt.

Delete Files Older Than X Days using Windows PowerShell

Get-ChildItem –Path  "C:\Your\Folder" –Recurse | Where-Object { $_.CreationTime –lt (Get-Date).AddDays(-7) } | Remove-Item

This command deletes all files that were created before 7 days.

To better suit your needs, this can be modified to inculde or exclude specific file types, like so:

Get-ChildItem –Path  "C:\Your\Folder" –Recurse -include *.log | Where-Object { $_.CreationTime –lt (Get-Date).AddDays(-5) } | Remove-Item

This will delete only those files that have *.log extension. To exclude certain files, use -exclude parameter.

In addition to CreationTime you can also delete files based on LastAccessTime or LastWriteTime (Modified) parameter.

Delete Files Older Than X Days using Command Prompt

forfiles -P "C:\Your\Folder" -S -M *.* -D -7 -C "CMD /C DEL @path"

-P: Specifies path to the folder that contains your files.
-S: Recurse into any subfolders.
-M: Search all files or limit to specific file type. Specify file type like this: *.log for all log files.
-D: Specifies modified date.
-C Run command enclosed in quotes.