Deleting the Oldest Log File

If you’re writing log activity to files, you may want to clean up things, so maybe you’d like to always delete the oldest log file when you add a new one.

Here is a simple approach:

# this is the folder keeping the log files
$LogFileDir = "c:myLogFiles"

# find all log files...
Get-ChildItem -Path $LogFileDir -Filter *.log |
  # sort by last change ascending
  # (oldest first)...
  Sort-Object -Property LastWriteTime |
  # take the first (oldest) one
  Select-Object -First 1 | 
  # remove it (remove -whatif to actually delete)
  Remove-Item -WhatIf

If you’d like to keep only the latest 5 files, change like this:

# this is the folder keeping the log files
$LogFileDir = "c:myLogFiles"
$Keep = 5

# find all log files...
$files = @(Get-ChildItem -Path $LogFileDir -Filter *.log)
$NumberToDelete = $files.Count - $Keep

if ($NumberToDelete -gt 0)
{
    $files |
      # sort by last change ascending
      # (oldest first)...
      Sort-Object -Property LastWriteTime |
      # take the first (oldest) one
      Select-Object -First $NumberToDelete | 
      # remove it (remove -whatif to actually delete)
      Remove-Item -WhatIf
}

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!

GD Star Rating
loading...