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

How to retrieve serial number from a server using ... In some situations the administrator has to retrieve the serial number of a server to check warranty and etc. In this Tutorial we are going over the p...
Software-Defined Networking with Windows Server an... Free online event with live QA with the WAP team: http://aka.ms/WAPIaaS Two half-days – Wednesday July 16th & Thursday July 17th – 9am-1pm PST ...
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...
How to enable routing among network adapters In this Tutorial we will show how to enable routing among network adapters in Windows Server 2012 R2 although the same procedure can be used on previo...