PowerShell: How to Move Files Older Than X Days


You can use the following syntax in PowerShell to move 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) |
Move-Item -Destination 'c:/users/bobbi/data1'

This particular example moves all files in the current directory that are more than 10 days old to a different folder named data1 in a specific location.

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

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

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

First, we can use the Get-ChildItem -File 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 7/6/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) |
Move-Item -Destination 'c:/users/bobbi/data1'

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

PowerShell move files older than X days

Notice that when we run the Get-ChildItem cmdlet again, we can see that the two files that were older than 10 days old have both been moved from the directory.

We can use the Get-ChildItem cmdlet to also view the files in the data1 folder:

We can see that both files that were older than 10 days in the data2 folder were successfully moved to the data1 folder.

Note: Feel free to change the -10 in the AddDays() function in the code to instead move 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 Move All Files from Folders and Subfolders into One Folder
PowerShell: How to Delete Files Matching a Certain Pattern
PowerShell: How to Delete All Files with Specific Extension
PowerShell: How to Delete File if it Exists

Leave a Reply