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.

Solution


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).

image11

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))

image8

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 }

image14

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.

image17

Conclusion


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 ITPROCentral.com, MSExchange.org, Techgenix.com and Anderson Patricio.org (Portuguese).

Related Post

Cluster Shared Volumes (CSV) errors on Hyper-V Clu... In a failover cluster, virtual machines can use Cluster Shared Volumes that are on the same LUN (disk), while still being able to fail over (or move f...
How to extend Azure Service Fabric to on-premise? You can deploy a Service Fabric cluster on any physical or virtual machine running the Windows Server operating system, including ones residing in you...
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...
Automating the process to join a server to a domai... In this Tutorial we are going to optimize a simple task that in larger environments may take some time from the service desk/operations team which is ...