Using PowerShell to remove files older than X days

Share this:

In this Tutorial we are going to use PowerShell to remove files based on their last time written.


The first step is to find a folder where we have several types of files such the one shown in the figure below. Notice that were modified in several dates (2013, 2014 and different months as well).


I’m lazy and I don’t want to specify the date but instead I want to provide the number of days that I want to keep it. For that goal we are going to use .AddDays(-100) and before testing that live on a script let’s run a simple test, as follows.

Write-Host ((Get-Date).AddDays(-100))


Based on the test above, we can add the cmdlet to get all items from the current folder and if they are older than X days (in our case 100 days) we will move them to the folder C:tmp

Get-ChildItem | Where { $_.LastWriteTime –lt ((Get-Date).AddDays(-100) ) ) | ForEach { Move-Item $_.Name –Destination C:Temp }


After running that script we can go to the folder where we moved the files (C:Tmp) and we will have only files older than 100 days there.



In this Tutorial we went over the process to remove files based on their last modified date. This procedure can be useful to move log files and any other type of file from a specific folder. In this Tutorial we just moved however in your environment you can start cleaning up using the Remove-Item cmdlet.

Written by Anderson Patricio

Anderson Patricio

Anderson Patricio is a Canadian MVP in Cloud and Datacenter Management, and Office Server and Services, besides the Microsoft Award he also holds a Solutions Master (MCSM) in Exchange and several other certifications. Anderson has been contributing to the Microsoft Community with articles, tutorials, blog posts, twitter, forums and book reviews. He is a regular contributor here at,, and Anderson (Portuguese).

Related Post

Containers on Azure – Part 2 On the previous post (see here), I talked about the concept of Containers, Azure Container Service and Azure Service Fabric. Now that you know the con...
Managing a Hyper-V Server Core installation using ... With all the benefits that Server Core bring such as performance, security and so on. But without the GUI, it's not easy to do the daily management an...
Integration between Hyper-V Network Virtualization... One of features on Windows Server 2012 R2 that was improved since the last version is network virtualization. Virtual networks are created by using Hy...
Backing up Hyper-V and virtual machines using Wind... Previous versions of Hyper-V (like 2008, 2008 R2 and 2008 R2 SP1) had complications and incompatibilities with the built-in backup tool, forcing the a...