On every SharePoint or IIS server I need the following script:
Short Version, e.g. for Windows Task Scheduler
powershell -command “get-childitem -path c:\inetpub\logs\logfiles -filter *.log -recurse | ? { $_.LastWriteTimeUtc -lt [datetime]::utcnow.addmonths(-2)} | remove-item -force -confirm:$false -whatif”
(You may need to adjust the path to the log files!)
Long Version
cls
$path = "C:\inetpub\logs"
$dt = [datetime]::Now
$s = [long]0
Get-ChildItem "$($path)\LogFiles" -Filter "*.log" -Recurse | % { $s += $_.Length }
Write-host "Size before: $($s / 1024 / 1024) MB"
$s = [long]0
Get-ChildItem "$($path)\LogFiles" -Filter "*.log" -Recurse | ? { ($dt - $_.LastWriteTime).TotalDays -gt 30 } | % { $s += $_.Length; $_ | Remove-Item -Confirm:$false -Force }
Write-host "Removed: $($s / 1024 / 1024) MB"
$s = [long]0
Get-ChildItem "$($path)\LogFiles" -Filter "*.log" -Recurse | % { $s += $_.Length }
Write-host "Size after: $($s / 1024 / 1024) MB"