Log File Cleanup

Here is a basic PowerShell script for cleaning up old files, it can be customized for number of days, file extension, and folder paths. I use this to help clean up my constantly growing SharePoint 2007 usage logs on my web front ends. After SharePoint processes them into SQL the log files are no longer needed and over time these old usage logs can take up lots of storage space.

 

#########################################
 # Log_Cleanup.ps1 #
 # #
 # Deletes files in target folder #
 # that are older than specified number #
 # of days #
 # #
 ########################################
 Function LogCleanup
 {
 ############################# Parameters ##########
 ## Delete all files older than this number of days
 $Days = "30"
 
 ## File types to delete
 $FileType = "*.log"
 
 ## Root folders to run cleanup separated by commas
 $TargetFolder = "C:\USAGE_LOG_FOLDER", "C:\SOME_OTHER_FOLDER"
  ## NOTE: Script WILL recurse each subfolder inside these folders
 ########################## End Parameters ##########
 if (Test-Path $TargetFolder)
 {
 $Now = Get-Date
 $LastWrite = $Now.AddDays(-$days)
 $Files = get-childitem $TargetFolder -include $FileType -recurse |Where {$_.LastWriteTime -le "$LastWrite"}
 foreach ($File in $Files)
 {write-host "Deleting file $File" -foregroundcolor "Yellow"; Remove-Item $File | out-null}
 }
 Else
 {Write-Host "Folder $TargetFolder Does not exist! Check folder path"}
 }
 LogCleanup