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

Restoring Hyper-V and Virtual Machines using Windo... Cluster, Hyper-V Replica, Storage Migration, and other features makes for a higher availability for Hyper-V virtual machines, but it is impossible to ...
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...
Software-Defined Networking with Windows Server an... Free online event with live QA with the WAP team: Two half-days – Wednesday July 16th & Thursday July 17th – 9am-1pm PST ...
MPIO on Hyper-V Server On the previous version of Windows Server (prior Windows Server 2012) you have to download and install MultiPath I/O (MPIO). Since Windows Server 2012...