Create a centralized logging system to track health check results over time and implement alerting for critical issues.
# Create centralized logging function
function Write-ADHealthLog {
param(
[string]$Message,
[string]$Level = "INFO",
[string]$LogPath = "C:\logs\ADHealth.log"
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "[$timestamp] [$Level] $Message"
# Ensure log directory exists
$logDir = Split-Path $LogPath -Parent
if (!(Test-Path $logDir)) {
New-Item -Path $logDir -ItemType Directory -Force
}
# Write to log file
Add-Content -Path $LogPath -Value $logEntry
# Also write to event log for critical issues
if ($Level -eq "ERROR" -or $Level -eq "CRITICAL") {
Write-EventLog -LogName "Application" -Source "AD Health Monitor" -EventId 1001 -EntryType Error -Message $Message
}
}
Create an alerting function for critical issues:
function Send-ADHealthAlert {
param(
[string]$AlertMessage,
[string]$Severity = "High",
[array]$Recipients = @("admin@yourdomain.com")
)
$subject = "[AD ALERT - $Severity] Active Directory Health Issue"
$body = @"
Active Directory Health Alert
Severity: $Severity
Timestamp: $(Get-Date)
Domain Controller: $env:COMPUTERNAME
Issue Details:
$AlertMessage
Please investigate immediately.
"@
try {
Send-MailMessage -To $Recipients -From "adalert@yourdomain.com" -Subject $subject -Body $body -SmtpServer "mail.yourdomain.com"
Write-ADHealthLog "Alert sent successfully: $AlertMessage" "INFO"
}
catch {
Write-ADHealthLog "Failed to send alert: $($_.Exception.Message)" "ERROR"
}
}
Integrate logging into your health checks:
# Example integration with DCDiag results
$dcdiagResults = dcdiag /test:DNS /test:FSMOCheck /v
if ($dcdiagResults -match "failed") {
$failedTests = $dcdiagResults | Where-Object { $_ -match "failed" }
$alertMessage = "DCDiag tests failed:`n" + ($failedTests -join "`n")
Write-ADHealthLog $alertMessage "ERROR"
Send-ADHealthAlert -AlertMessage $alertMessage -Severity "High"
}
else {
Write-ADHealthLog "All DCDiag tests passed" "INFO"
}
Test the logging and alerting system:
# Test logging
Write-ADHealthLog "Test log entry" "INFO"
# Test alerting
Send-ADHealthAlert -AlertMessage "Test alert message" -Severity "Low"
# Verify log file
Get-Content "C:\logs\ADHealth.log" -Tail 5
Pro tip: Set up log rotation to prevent log files from growing too large. Use PowerShell to archive logs older than 30 days automatically.