Implement monitoring to track the cleanup task's performance and catch any issues before they impact your Exchange server.
Create a simple logging mechanism by modifying your script execution. Create a wrapper script that logs results:
# Create a logging wrapper script
$LogFile = "C:\Scripts\ExchangeCleanupLog.txt"
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
try {
$Output = & "C:\Scripts\CleanExchangeLogFiles.ps1" -Days 7 -NoConfirmation 2>&1
Add-Content -Path $LogFile -Value "$Timestamp - SUCCESS: $Output"
} catch {
Add-Content -Path $LogFile -Value "$Timestamp - ERROR: $($_.Exception.Message)"
}
Save this as C:\Scripts\ExchangeCleanupWrapper.ps1 and update your scheduled task to call this wrapper instead.
Set up a simple monitoring check using PowerShell:
# Create a monitoring script to check disk space and task status
$DiskSpace = Get-WmiObject -Class Win32_LogicalDisk | Where-Object {$_.DeviceID -eq "C:"}
$FreeSpaceGB = [math]::Round($DiskSpace.FreeSpace/1GB,2)
$TaskInfo = Get-ScheduledTask -TaskName "Exchange Log Cleanup" | Get-ScheduledTaskInfo
if ($FreeSpaceGB -lt 5) {
Write-Warning "Low disk space detected: $FreeSpaceGB GB remaining"
}
if ($TaskInfo.LastTaskResult -ne 0) {
Write-Warning "Last cleanup task failed with result code: $($TaskInfo.LastTaskResult)"
}
Configure Windows Event Log monitoring for critical events:
# Set up event log monitoring for disk space issues
wevtutil sl "Microsoft-Windows-Kernel-General/Analytic" /e:true
Verify your monitoring setup by checking the log file after the next scheduled run:
Get-Content "C:\Scripts\ExchangeCleanupLog.txt" -Tail 5
Pro tip: Set up email alerts using PowerShell's Send-MailMessage cmdlet in your wrapper script to notify you of cleanup failures or when disk space drops below critical thresholds.