Prune System Log Files

By James|05/20/2020|,

Introduction

Let's face it, logs are everywhere.  It seems like every piece of software creates log files these days.  Unfortunately, not every piece of software cleans up after itself or allows setting limits on the amount of logging to create and retain.  This can bring down a system if log file storage is not kept in check.

Resolution

The following PowerShell script will prune log files older than 60 days.  Modify the $DaysToKeep variable to change how many days worth of logs are kept.  At the bottom of the script, initiate the PruneLogFiles function with the folder(s) to prune.  Finally, use the Windows Task Scheduler to create a scheduled task.  Personally, I run the script weekly.  Enjoy!

# Title: PruneLogFiles.ps1
# Version: 1.0, 13 MAY 2020
# Author: James Sanders
# Purpose: Delete old log files

# Set allowable extensions to prune
$LogExt = @("*.evt", "*.log")

# How many days of logs to keep
$DaysToKeep = 60

Function PruneLogFiles ($LogPath) {
  Write-Host
  If (!(Test-Path $LogPath)) {
    Write-Host "$LogPath does not exit"
    Return
  }
  Write-Host "Examining $LogPath"
  $LogFiles = Get-ChildItem $LogPath -Recurse -File -Include $LogExt -Attributes !ReadOnly, !System, !Hidden | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-$DaysToKeep)}
  If (!($LogFiles)) {
    Write-Host "No log files ($LogExt) to process"
    Return
  }
  Write-Host "Deleting" $LogFiles.Count "log files"
  ForEach ($LogFile in $LogFiles) {
    $LogFile.Delete()
  }
  Return
}

Write-Host
Write-Host "Keeping $DaysToKeep days of logs"

PruneLogFiles D:\Logs\OS
PruneLogFiles D:\Logs\SMTP

 

Copyright 2011 - 2024 The Lazy IT Admin | All Rights Reserved
menu-circlecross-circle linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram