Delete old log files with PowerShell

Today I came across a folder full of log files created by an import/integration application on one of our servers. The folder contained over 50,000 files. Rather than manually delete the old logs, here’s how I removed all items older than 1 month:

Get-ChildItem "C:Path_To_logs*.txt" | Where-Object {$_.CreationTime -lt (Get-Date).AddMonths(-1)} | Remove-Item -Force -Verbose -WhatIf

Since PowerShell is based on the .NET Framework, you can use standard System.DateTime methods when working with dates and times.

PS C:> Get-Date | Get-Member Add*


   TypeName: System.DateTime

Name            MemberType Definition
----            ---------- ----------
Add             Method     datetime Add(timespan value)
AddDays         Method     datetime AddDays(double value)
AddHours        Method     datetime AddHours(double value)
AddMilliseconds Method     datetime AddMilliseconds(double value)
AddMinutes      Method     datetime AddMinutes(double value)
AddMonths       Method     datetime AddMonths(int months)
AddSeconds      Method     datetime AddSeconds(double value)
AddTicks        Method     datetime AddTicks(long value)
AddYears        Method     datetime AddYears(int value)

Passing a negative value to one of the Add* methods will result in subtracting that amount of time:

PS C:> Get-Date
Wednesday, 12 August 2015 2:37:23 PM

PS C:> (Get-Date).AddMonths(1)
Saturday, 12 September 2015 2:37:37 PM

PS C:> (Get-Date).AddMonths(-1)
Sunday, 12 July 2015 2:37:40 PM

Obviously you need to be very careful with specifying a path to a command like Remove-Item. I’ve left the -WhatIf switch on the example code above.

It’s easy to add something like this to a scheduled task to keep a log folder tidy.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s