Cleaning Week: Deleting Log File Backups

by May 31, 2016

In a previous tip you learned that there may be gigabytes worth of log file CAB files. Today, let’s try and have PowerShell do the cleanup. All of these CAB files can safely be removed.

#requires -Version 3
#Requires -RunAsAdministrator
# must run with admin privileges!


# use an ordered hash table to store logging info
$sizes = [Ordered]@{}



Get-ChildItem -Path $env:windir\logs\cbs\ -Filter *.cab | 
ForEach-Object {
  try 
  { 
    $fileSize = $_.Length
    # ATTENTION: REMOVE -WHATIF AT OWN RISK
    # WILL DELETE FILES AND RETRIEVE STORAGE SPACE
    # ONLY AFTER YOU REMOVED -WHATIF
    Remove-Item -Path $_.FullName -ErrorAction SilentlyContinue -WhatIf
    $sizes['Retrieved'] += $fileSize
  }
  catch {}
}

# turn bytes into MB
$Sizes['RetrievedMB'] = [Math]::Round(($Sizes['Retrieved']/1MB), 1)

New-Object -TypeName PSObject -Property $sizes

Note that the code will not actually delete anything. It just reports what would have been deleted, and how much space you could retrieve. You must remove the -WhatIf parameter in the code (on your own risk) to actually delete things.

The longer you ran your system the more data can be retrieved. On a new system, it might just be a couple of megabytes. On a system that has been up and running for a year or so, you might be able to free many gigabytes.

Twitter This Tip! ReTweet this Tip!