Tuesday, June 09, 2020

Exchange Logging: Clear out the log files

Here is a simple PowerShell script that you can run against Exchange either manually as part of your maintenance routine or with Task Scheduler to clear out files when you need to.

I must admit the first time I ran this on my Exchange 2013 server it took almost 5 minutes to complete and freed up over 30G of drive space from the multiple years of log files hidden all over.

At the top of the script make sure you change the drive letter if needed to match where your Exchange log files are stored.  Sadly I have seen many Exchange servers over the years with everything installed on C: so this script just assumes that.

NOTE:  Please make sure you have good backups in place and/or a snapshot of your virtual machine before running this.  While I have tested the script with no negative effects, please do not assume this will always be the case.  There is no substitution for good backups and a quick recovery plan if needed.

If you want to run the file manually, just open PowerShell as administrator, navigate to where you have your script file saved (Example Name:  ClearFiles.ps1).  From there just type in ./ClearFiles.ps1 and wait on the script to complete the cleanup.

Good luck.

Set-Executionpolicy RemoteSigned
$days=2
$IISLogPath="C:\inetpub\logs\LogFiles\"
$ExchangeLoggingPath="C:\Program Files\Microsoft\Exchange Server\V15\Logging\"
$ETLLoggingPath="C:\Program Files\Microsoft\Exchange Server\V15\Bin\Search\Ceres\Diagnostics\ETLTraces\"
$ETLLoggingPath2="C:\Program Files\Microsoft\Exchange Server\V15\Bin\Search\Ceres\Diagnostics\Logs"
Function CleanLogfiles($TargetFolder)
{
    if (Test-Path $TargetFolder) {
        $Now = Get-Date
        $LastWrite = $Now.AddDays(-$days)
        $Files = Get-ChildItem $TargetFolder -Include *.log,*.blg, *.etl, *.txt -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}
        foreach ($File in $Files)
            {Write-Host "Deleting file $File" -ForegroundColor "white"; Remove-Item $File -ErrorAction SilentlyContinue | out-null}
       }
Else {
    Write-Host "The folder $TargetFolder doesn't exist! Check the folder path!" -ForegroundColor "white"
    }
}
CleanLogfiles($IISLogPath)
CleanLogfiles($ExchangeLoggingPath)
CleanLogfiles($ETLLoggingPath)
CleanLogfiles($ETLLoggingPath2)