I found an excellent article here that provided a nice PowerShell script to help automate the cleanup of Exchange related log files (tested on 2013/2016/2019). I made a few modifications to add the following functonality
- Support for command line parameters for base paths and number of days to keep
- Support for WhatIf Parameter
- Loading of default values for the paths from the registry
- Keeping track of and displaying the amount of file space recovered
[CmdletBinding(SupportsShouldProcess)] param( [string] $ExchangePath = (Split-Path (Get-ItemPropertyValue HKLM:SOFTWARE\Microsoft\ExchangeServer\v15\Diagnostics MsiInstallPath)), [string] $IISPath = (Split-Path (Get-ItemPropertyValue HKLM:SOFTWARE\Microsoft\InetStp PathWWWRoot)), [int] $NumberOfDaysToKeep = 2 ) # Set execution policy if not set $ExecutionPolicy = Get-ExecutionPolicy if ($ExecutionPolicy -ne "RemoteSigned") { Set-ExecutionPolicy RemoteSigned -Force } # Cleanup logs older than the set of days in numbers $days = $NumberOfDaysToKeep # Path of the logs that you like to cleanup $IISLogPath = "$IISPath\logs\LogFiles\" $ExchangeLoggingPath = "$ExchangePath\Logging\" $ETLLoggingPath = "$ExchangePath\Bin\Search\Ceres\Diagnostics\ETLTraces\" $ETLLoggingPath2 = "$ExchangePath\Bin\Search\Ceres\Diagnostics\Logs\" # Clean the logs Function CleanLogfiles($TargetFolder) { Write-Host -Debug -ForegroundColor Green "Processing: $TargetFolder" $TotalSize = 0 if (Test-Path $TargetFolder) { $Now = Get-Date $LastWrite = $Now.AddDays(-$days) $Files = Get-ChildItem $TargetFolder -Recurse | Where-Object { $_.Name -like "*.log" -or $_.Name -like "*.blg" -or $_.Name -like "*.etl" } | Where-Object { $_.lastWriteTime -le "$lastwrite" } | Select-Object FullName foreach ($File in $Files) { $FullFileName = $File.FullName if (Test-Path $FullFileName -ErrorAction SilentlyContinue) { $TotalSize += (Get-Item -Path $FullFileName).Length Write-Host "`tDeleting: $FullFileName" -ForegroundColor Yellow Remove-Item $FullFileName -ErrorAction SilentlyContinue -WhatIf:$WhatIfPreference | out-null } else { Write-Host "`tCannot Access: $FullFileName" -ForegroundColor Red } } Write-Host "`tTotal Space Recovered: $($($TotalSize/1GB).ToString('#.#')) Gb" -ForegroundColor Cyan } Else { Write-Host "The folder $TargetFolder doesn't exist! Check the folder path!" -ForegroundColor "red" } return $TotalSize } $spaceRecovered += CleanLogfiles($IISLogPath) $spaceRecovered += CleanLogfiles($ExchangeLoggingPath) $spaceRecovered += CleanLogfiles($ETLLoggingPath) $spaceRecovered += CleanLogfiles($ETLLoggingPath2) Write-Host "Total Space Recovered: $($($spaceRecovered/1GB).ToString('#.#')) Gb" -ForegroundColor Cyan