PowerShell: How to Delete Files Older Than X Days


You can use the following syntax in PowerShell to delete all files in a directory that are older than a specific number of days:

Get-ChildItem -Recurse -File | Where LastWriteTime -lt (Get-Date).AddDays(-10) | Remove-Item -Force

This particular example deletes all files in the current directory that are more than 10 days old.

Note that we use LastWriteTime to extract the date and time of when a file was last modified.

If you’d like, you can use CreationTime to instead use the date and time of when a file was last created.

The following example shows how to use this syntax in practice.

Example: How to Delete All Files Older Than X Days Using PowerShell

Suppose that we would like to delete all files in our current directory that have been modified more than 10 days ago.

First, we can use the Dir command to view each of the files in our current directory:

We can see that there are five files in this directory with various LastWriteTime datetimes.

Note that this article is currently being written on 6/12/2024. Suppose that we would like to delete all files older than 10 days.

We can use the following syntax to do so:

Get-ChildItem -Recurse -File | Where LastWriteTime -lt (Get-Date).AddDays(-10) | Remove-Item -Force

The following screenshot shows how to use this syntax in practice:

PowerShell delete files older than X days

Notice that when we run the Dir command again, we can see that the two files that were older than 10 days old have both been deleted from the directory.

Note: Feel free to change the -10 in the AddDays() function in the code to instead delete files that are older than a different number of days.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Delete Files Matching a Certain Pattern
PowerShell: How to Delete File if it Exists
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply