# .NOTES The script correctly performs these AD health checks: DNS resolution and ping connectivity Service status (DNS, NTDS, NetLogon) Disk space monitoring with color-coded alerts Time synchronization validation Comprehensive DCDiag tests (21 different tests) FSMO role identification Uptime monitoring The HTML report output is well-formatted with color coding for pass/warn/fail status. The script is production-ready for AD health monitoring. This script is completely safe for production AD environments. It performs only read-only operations and will not cause any disruption. Here's what the script does (all non-disruptive): Read-Only Operations: DNS lookups (Resolve-DnsName) Network connectivity tests (Test-Connection) Service status queries (Get-Service) System information queries (Get-CimInstance) Time synchronization checks (w32tm /stripchart) DCDiag diagnostic tests (designed for production use) No Changes Made: ❌ No service restarts ❌ No configuration modifications ❌ No AD object changes ❌ No registry modifications Minimal Impact: Light network traffic from connectivity tests Standard WMI queries (same as monitoring tools) DCDiag tests are Microsoft's official diagnostic tools used regularly in production Best Practices for Production: Run during business hours (generates useful real-time health data) Consider running from a management workstation rather than a DC The script includes progress indicators so you can monitor execution This type of health check script is commonly run by AD administrators as part of routine maintenance and monitoring. Microsoft's DCDiag tool (which this script uses) is specifically designed for production diagnostics. .SYNOPSIS Get-ADHealth.ps1 - Domain Controller Health Check Script. .DESCRIPTION This script performs a list of common health checks to a specific domain, or the entire forest. The results are then compiled into a colour coded HTML report. .OUTPUTS The results are currently only output to HTML for email or as an HTML report file, or sent as an SMTP message with an HTML body. .PARAMETER DomainName Perform a health check on a specific Active Directory domain. .PARAMETER ReportFile Output the report details to a file in the current directory. .PARAMETER SendEmail Send the report via email. You have to configure the correct SMTP settings. .EXAMPLE .\Get-ADHealth.ps1 -ReportFile Checks all domains and all domain controllers in your current forest and creates a report. .EXAMPLE .\Get-ADHealth.ps1 -DomainName alitajran.com -ReportFile Checks all the domain controllers in the specified domain "alitajran.com" and creates a report. .EXAMPLE .\Get-ADHealth.ps1 -DomainName alitajran.com -SendEmail Checks all the domain controllers in the specified domain "alitajran.com" and sends the resulting report as an email message. .LINK alitajran.com/active-directory-health-check-powershell-script #> [CmdletBinding()] Param( [Parameter( Mandatory = $false)] [string]$DomainName, [Parameter( Mandatory = $false)] [switch]$ReportFile, [Parameter( Mandatory = $false)] [switch]$SendEmail ) #................................... # Global Variables #................................... $allTestedDomainControllers = [System.Collections.Generic.List[Object]]::new() $allDomainControllers = [System.Collections.Generic.List[Object]]::new() $now = Get-Date $date = $now.ToShortDateString() $reportTime = $now $reportFileNameTime = $now.ToString("yyyyMMdd_HHmmss") $reportemailsubject = "Domain Controller Health Report" $smtpsettings = @{ To = 'email@domain.com' From = 'adhealth@yourdomain.com' Subject = "$reportemailsubject - $date" SmtpServer = "mail.domain.com" Port = "25" #Credential = (Get-Credential) #UseSsl = $true } #................................... # Functions #................................... # This function gets all the domains in the forest. Function Get-AllDomains() { Write-Verbose "Running function Get-AllDomains" $allDomains = (Get-ADForest).Domains return $allDomains } # This function gets all the domain controllers in a specified domain. Function Get-AllDomainControllers ($ComputerName) { Write-Verbose "Running function Get-AllDomainControllers" $allDomainControllers = Get-ADDomainController -Filter * -Server $ComputerName | Sort-Object HostName return $allDomainControllers } # This function tests the domain controller against DNS. Function Get-DomainControllerNSLookup($ComputerName) { Write-Verbose "Running function Get-DomainControllerNSLookup" try { $domainControllerNSLookupResult = Resolve-DnsName $ComputerName -Type A | Select-Object -ExpandProperty IPAddress if ($domainControllerNSLookupResult) { $domainControllerNSLookupResult = 'Success' } else { $domainControllerNSLookupResult = 'Fail' } } catch { $domainControllerNSLookupResult = 'Fail' } return $domainControllerNSLookupResult } # This function tests the connectivity to the domain controller. Function Get-DomainControllerPingStatus($ComputerName) { Write-Verbose "Running function Get-DomainControllerPingStatus" if ((Test-Connection $ComputerName -Count 1 -quiet) -eq $True) { $domainControllerPingStatus = "Success" } else { $domainControllerPingStatus = 'Fail' } return $domainControllerPingStatus } # This function tests the domain controller uptime. Function Get-DomainControllerUpTime($ComputerName) { Write-Verbose "Running function Get-DomainControllerUpTime" if ((Test-Connection $ComputerName -Count 1 -Quiet) -eq $True) { try { $W32OS = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $ComputerName -ErrorAction SilentlyContinue $timespan = (Get-Date) - $W32OS.LastBootUpTime [int]$uptime = "{0:00}" -f $timespan.TotalHours } catch { $uptime = 'CIM Failure' } } else { $uptime = 'Fail' } return $uptime } # This function checks the time synchronization offset. function Get-TimeDifference($ComputerName) { Write-Verbose "Running function Get-TimeDifference" if ((Test-Connection $ComputerName -Count 1 -Quiet) -eq $True) { try { $currentTime, $timeDifference = (& w32tm /stripchart /computer:$ComputerName /samples:1 /dataonly)[-1].Trim("s") -split ',\s*' $diff = [double]$timeDifference $diffRounded = [Math]::Round($diff, 1, [MidPointRounding]::AwayFromZero) } catch { $diffRounded = 'Fail' } } else { $diffRounded = 'Fail' } return $diffRounded } # This function checks the DNS, NTDS and Netlogon services. Function Get-DomainControllerServices($ComputerName) { Write-Verbose "Running function DomainControllerServices" $thisDomainControllerServicesTestResult = [PSCustomObject]@{ DNSService = $null NTDSService = $null NETLOGONService = $null } if ((Test-Connection $ComputerName -Count 1 -quiet) -eq $True) { if ((Get-Service -ComputerName $ComputerName -Name DNS -ErrorAction SilentlyContinue).Status -eq 'Running') { $thisDomainControllerServicesTestResult.DNSService = 'Success' } else { $thisDomainControllerServicesTestResult.DNSService = 'Fail' } if ((Get-Service -ComputerName $ComputerName -Name NTDS -ErrorAction SilentlyContinue).Status -eq 'Running') { $thisDomainControllerServicesTestResult.NTDSService = 'Success' } else { $thisDomainControllerServicesTestResult.NTDSService = 'Fail' } if ((Get-Service -ComputerName $ComputerName -Name netlogon -ErrorAction SilentlyContinue).Status -eq 'Running') { $thisDomainControllerServicesTestResult.NETLOGONService = 'Success' } else { $thisDomainControllerServicesTestResult.NETLOGONService = 'Fail' } } else { $thisDomainControllerServicesTestResult.DNSService = 'Fail' $thisDomainControllerServicesTestResult.NTDSService = 'Fail' $thisDomainControllerServicesTestResult.NETLOGONService = 'Fail' } return $thisDomainControllerServicesTestResult } # This function runs the DCDiag tests and saves them in a variable for later processing. Function Get-DomainControllerDCDiagTestResults($ComputerName) { Write-Verbose "Running function Get-DomainControllerDCDiagTestResults" # Initialize the object with all properties set to null $DCDiagTestResults = [PSCustomObject]@{ ServerName = $ComputerName Connectivity = $null Advertising = $null FrsEvent = $null DFSREvent = $null SysVolCheck = $null KccEvent = $null KnowsOfRoleHolders = $null MachineAccount = $null NCSecDesc = $null NetLogons = $null ObjectsReplicated = $null Replications = $null RidManager = $null Services = $null SystemLog = $null VerifyReferences = $null CheckSDRefDom = $null CrossRefValidation = $null LocatorCheck = $null Intersite = $null FSMOCheck = $null } if ((Test-Connection $ComputerName -Count 1 -quiet) -eq $True) { # Define an array of parameters for Dcdiag.exe $params = @( "/s:$ComputerName", "/test:Connectivity", "/test:Advertising", "/test:FrsEvent", "/test:DFSREvent", "/test:SysVolCheck", "/test:KccEvent", "/test:KnowsOfRoleHolders", "/test:MachineAccount", "/test:NCSecDesc", "/test:NetLogons", "/test:ObjectsReplicated", "/test:Replications", "/test:RidManager", "/test:Services", "/test:SystemLog", "/test:VerifyReferences", "/test:CheckSDRefDom", "/test:CrossRefValidation", "/test:LocatorCheck", "/test:Intersite", "/test:FSMOCheck" ) $DCDiagTest = (Dcdiag.exe @params) -split ('[\r\n]') $TestName = $null $TestStatus = $null $DCDiagTest | ForEach-Object { switch -Regex ($_) { "Starting test:" { $TestName = ($_ -replace ".*Starting test:").Trim() } "passed test|failed test" { $TestStatus = if ($_ -match "passed test") { "Passed" } else { "Failed" } } } if ($TestName -and $TestStatus) { # Set the property value directly $DCDiagTestResults.$TestName = $TestStatus $TestName = $null $TestStatus = $null } } } else { # If the domain controller is not reachable, set all tests to 'Failed' foreach ($property in $DCDiagTestResults.PSObject.Properties.Name) { if ($property -ne "ServerName") { $DCDiagTestResults.$property = "Failed" } } } return $DCDiagTestResults } # This function checks the free space in percentage on the OS drive Function Get-DomainControllerOSDriveFreeSpace ($ComputerName) { Write-Verbose "Running function Get-DomainControllerOSDriveFreeSpace" if ((Test-Connection $ComputerName -Count 1 -Quiet) -eq $True) { try { $thisOSDriveLetter = (Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $ComputerName -ErrorAction Stop).SystemDrive $thisOSDiskDrive = Get-CimInstance -ClassName Win32_LogicalDisk -ComputerName $ComputerName -Filter "DeviceID='$thisOSDriveLetter'" -ErrorAction Stop $thisOSPercentFree = [math]::Round($thisOSDiskDrive.FreeSpace / $thisOSDiskDrive.Size * 100) } catch { $thisOSPercentFree = 'CIM Failure' } } else { $thisOSPercentFree = "Fail" } return $thisOSPercentFree } # This function checks the free disk space on the OS drive in GB Function Get-DomainControllerOSDriveFreeSpaceGB ($ComputerName) { Write-Verbose "Running function Get-DomainControllerOSDriveFreeSpaceGB" if ((Test-Connection $ComputerName -Count 1 -Quiet) -eq $True) { try { $thisOSDriveLetter = (Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $ComputerName -ErrorAction Stop).SystemDrive $thisOSDiskDrive = Get-CimInstance -ClassName Win32_LogicalDisk -ComputerName $ComputerName -Filter "DeviceID='$thisOSDriveLetter'" -ErrorAction Stop # Convert bytes to GB, rounding to 2 decimal places $freeSpaceGB = [math]::Round($thisOSDiskDrive.FreeSpace / 1GB, 2) } catch { $freeSpaceGB = 'CIM Failure' } } else { $freeSpaceGB = 'Fail' } return $freeSpaceGB } # This function generates HTML code from the results of the above functions. Function New-ServerHealthHTMLTableCell() { param( $lineitem ) $htmltablecell = $null switch ($($reportline."$lineitem")) { "Success" { $htmltablecell = "
| Server | Site | OS Version | IPv4 Address | Operation Master Roles | DNS | Ping | Uptime (hours) | OS Free Space (%) | OS Free Space (GB) | Time offset (seconds) | DNS Service | NTDS Service | NetLogon Service | DCDIAG: Connectivity | DCDIAG: Advertising | DCDIAG: FrsEvent | DCDIAG: DFSREvent | DCDIAG: SysVolCheck | DCDIAG: KccEvent | DCDIAG: FSMO KnowsOfRoleHolders | DCDIAG: MachineAccount | DCDIAG: NCSecDesc | DCDIAG: NetLogons | DCDIAG: ObjectsReplicated | DCDIAG: Replications | DCDIAG: RidManager | DCDIAG: Services | DCDIAG: SystemLog | DCDIAG: VerifyReferences | DCDIAG: CheckSDRefDom | DCDIAG: CrossRefValidation | DCDIAG: LocatorCheck | DCDIAG: Intersite | DCDIAG: FSMO Check | Processing Time (seconds) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| $($reportline.Server) | " $htmltablerow += "$($reportline.Site) | " $htmltablerow += "$($reportline."OS Version") | " $htmltablerow += "$($reportline."IPv4 Address") | " $htmltablerow += "$fsmoRoleHTML | " $htmltablerow += (New-ServerHealthHTMLTableCell "DNS" ) $htmltablerow += (New-ServerHealthHTMLTableCell "Ping") if ($($reportline."Uptime (hours)") -eq "CIM Failure") { $htmltablerow += "Could not test server uptime. | " } elseif ($($reportline."Uptime (hours)") -eq "Fail") { $htmltablerow += "Fail | " } else { $hours = [int]$($reportline."Uptime (hours)") if ($hours -le 24) { $htmltablerow += "$hours | " } else { $htmltablerow += "$hours | " } } $osSpace = $reportline."OS Free Space (%)" if ($osSpace -eq "CIM Failure") { $htmltablerow += "Could not test server free space. | " } elseif ($osSpace -eq "Fail") { $htmltablerow += "$osSpace | " } elseif ($osSpace -le 5) { $htmltablerow += "$osSpace | " } elseif ($osSpace -le 30) { $htmltablerow += "$osSpace | " } else { $htmltablerow += "$osSpace | " } $osSpaceGB = $reportline."OS Free Space (GB)" if ($osSpaceGB -eq "CIM Failure") { $htmltablerow += "Could not test server free space. | " } elseif ($osSpaceGB -eq "Fail") { $htmltablerow += "$osSpaceGB | " } elseif ($osSpaceGB -lt 5) { $htmltablerow += "$osSpaceGB | " } elseif ($osSpaceGB -lt 10) { $htmltablerow += "$osSpaceGB | " } else { $htmltablerow += "$osSpaceGB | " } $time = $reportline."Time offset (seconds)" if ($time -ge 1) { $htmltablerow += "$time | " } else { $htmltablerow += "$time | " } $htmltablerow += (New-ServerHealthHTMLTableCell "DNS Service") $htmltablerow += (New-ServerHealthHTMLTableCell "NTDS Service") $htmltablerow += (New-ServerHealthHTMLTableCell "NetLogon Service") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: Connectivity") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: Advertising") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: FrsEvent") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: DFSREvent") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: SysVolCheck") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: KccEvent") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: FSMO KnowsOfRoleHolders") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: MachineAccount") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: NCSecDesc") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: NetLogons") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: ObjectsReplicated") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: Replications") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: RidManager") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: Services") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: SystemLog") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: VerifyReferences") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: CheckSDRefDom") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: CrossRefValidation") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: LocatorCheck") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: Intersite") $htmltablerow += (New-ServerHealthHTMLTableCell "DCDIAG: FSMO Check") $processingTime = $reportline."Processing Time (seconds)" $htmltablerow += "$processingTime | " [array]$serverhealthhtmltable += $htmltablerow } $serverhealthhtmltable += "