Using PowerShell to remove files older than X days

Share

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 Exchange Server MVP and MCSM (Solutions Master) and he contributes to the Microsoft Community with articles, tutorials, blog posts, forums and book reviews. He is a regular contributor at MSExchange.org, AndersonPatricio.ca (English) and AndersonPatricio.org (Portuguese).
You can connect with Anderson on Twitter , Facebook, and Google+.