Scheduled PowerShell Script to Clean Up Disk Space in Exchange 2016

We had prepared a scheduled PowerShell Script to clean up disk space in Exchange 2016 to prevent the generated logs file from filling up C or D Drive

PowerShell Script to delete .log, .blg, and .etl files older than 14 days in D:\program files\microsoft\exchange server\V15\Logging and save it to C:\Scripts\ClearIISLogs.ps1

#Remove .log, .blg and .etl file in V15/Logging folder older than 14 Days
$LoggingFolder = "D:\program files\microsoft\exchange server\V15\Logging"

Get-ChildItem $LoggingFolder -Recurse | 
Where-Object {$_.Name -like "*.log" -or $_.Name -like "*.blg" -or $_.Name -like "*.etl"} | 
? LastWriteTime -lt (Get-Date).AddDays(-14) | Remove-Item 

PowerShell Script to delete IIS log files older than 14 days in C:\inetpub\logs\LogFiles\W3SVC1 and C:\inetpub\logs\LogFiles\W3SVC2 and save it to C:\Scripts\ClearLoggingFolder.ps1

#Cleanup IIS Logs
$limit = (Get-Date).AddDays(-14)
$path1 = "C:\inetpub\logs\LogFiles\W3SVC1"
$path2 = “C:\inetpub\logs\LogFiles\W3SVC2"

# Delete logs older than the $limit.
Get-ChildItem -Path $path1 -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
Get-ChildItem -Path $path2 -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

Schedule Tasks to run on every sunday at 1PM

#New ScheduleTask to clear .log, .blg & .etl files in D:\program files\microsoft\exchange server\V15\Logging on sunday at 1PM
$Action = New-ScheduledTaskAction -Execute 'Powershell.exe' `
-Argument '-NonInteractive -WindowStyle Hidden -command "C:\Scripts\ClearLoggingFolder.ps1"'

$Trigger =  New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -at 1PM 

Register-ScheduledTask -Action $Action -Trigger $Trigger -TaskName "ClearExchangeLoggingFolder" -Description "Clear files in Exchange 2016 Logging Folder" `
-User "$($env:USERDOMAIN)\$($env:USERNAME)" -Password "P@ssw0rd1234" 

Leave a Comment