Tuesday, October 4, 2016

Automatically clean up old IIS logs with PowerShell

Hi

Today I'm gonna share a new tip with you. It's regarding an automated way to clean logs file, either IIS log files or any other log been generated like SharePoint Logs...

There is a powershell script in Technet, but it contains an error , source link Automatically clean up old IIS logs with PowerShell

Hereunder you can find the script corrected and tested.

PowerShell
$LogPath = "C:\inetpub\logs" 
$maxDaystoKeep = -30 
$outputPath = "c:\CleanupTask\Cleanup_Old_logs.log" 
  
$itemsToDelete = dir $LogPath -Recurse -File *.log | Where LastWriteTime -lt ((get-date).AddDays($maxDaystoKeep)) 
  
if ($itemsToDelete.Count -gt 0){ 
    ForEach ($item in $itemsToDelete){ 
        "$($item.BaseName) is older than $((get-date).AddDays($maxDaystoKeep)) and will be deleted" | Add-Content $outputPath 
        Get-item $item.PSPath | Remove-Item -Verbose 
    } 
} 
ELSE{ 
    "No items to be deleted today $($(Get-Date).DateTime)"  | Add-Content $outputPath 
    } 
   
Write-Output "Cleanup of log files older than $((get-date).AddDays($maxDaystoKeep)) completed..." 
start-sleep -Seconds 10
 
I deployed this as a Scheduled Task and it’s running wonderfully. Enjoy!