# Script to validate an Active Directory Domain Controller's operational status
# Requires: ActiveDirectory PowerShell module and Domain Admin / Account Operator privileges

# Ensure AD Module is available
if (-not (Get-Module -ListAvailable -Name ActiveDirectory)) {
    Write-Error "The ActiveDirectory module is required to run this script. Please install RSAT."
    exit
}

# Set the target domain controller name
$DCName = Read-Host "Enter the Domain Controller Name (FQDN or Hostname)"

try {
    # Check if the DC is online and retrievable
    Write-Host "Verifying Domain Controller existence..." -ForegroundColor Cyan
    $DC = Get-ADDomainController -Identity $DCName -ErrorAction Stop
    Write-Host "Domain Controller '$DCName' found online." -ForegroundColor Green

    ---

    # Test Critical Services (Replaces the invalid Test-ComputerSecureChannel logic)
    Write-Host "`nChecking Critical AD Services..." -ForegroundColor Cyan
    $CriticalServices = @("NTDS", "Netlogon", "SamSs", "W32Time", "DNS")
    try {
        $Services = Get-Service -ComputerName $DCName -Name $CriticalServices -ErrorAction Stop
        foreach ($Service in $Services) {
            if ($Service.Status -eq "Running") {
                Write-Host "  Service $($Service.Name) is Running." -ForegroundColor Green
            } else {
                Write-Warning "  Service $($Service.Name) is $($Service.Status)!"
            }
        }
    } catch {
        Write-Warning "Failed to query services on '$DCName'. Check RPC/firewall settings."
    }

    ---

    # Check DNS Registration
    Write-Host "`nChecking DNS Registration..." -ForegroundColor Cyan
    try {
        $Test = Resolve-DnsName -Name $DC.ForceLogonDC -ErrorAction Stop
        if ($Test) {
            Write-Host "DNS registration is OK." -ForegroundColor Green
        }
    } catch {
        Write-Warning "DNS resolution failed for '$DCName'."
    }

    ---

    # Check Replication Status
    Write-Host "`nChecking Replication Status..." -ForegroundColor Cyan
    try {
        $ReplicationStatuses = Get-ADReplicationStatus -DomainController $DCName -ErrorAction Stop
        $ReplFailures = 0

        foreach ($Status in $ReplicationStatuses) {
            # 0 indicates success in AD replication cycles
            if ($Status.LastReplicationSuccess -eq 0 -or $Status.LastAttemptResult -eq "Success") {
                continue
            } else {
                Write-Warning "  Replication Link Failed: Partner ($($Status.Partner)) -> Result: $($Status.LastAttemptResult)"
                $ReplFailures++
            }
        }

        if ($ReplFailures -eq 0) {
            Write-Host "All replication links are healthy." -ForegroundColor Green
        }
    } catch {
        Write-Warning "Failed to check replication status. Ensure you have proper replication viewing permissions."
    }

    ---

    # Check Directory Services Event Logs for Errors
    Write-Host "`nChecking Directory Services Event Logs (Last 10 Errors)..." -ForegroundColor Cyan
    try {
        # Changed to 'Directory Service' log as it is far more relevant to DC health than 'Application'
        $ErrorEvents = Get-WinEvent -ComputerName $DCName -LogName "Directory Service" -MaxEvents 10 -FilterHashtable @{Level=2} -ErrorAction SilentlyContinue
        if ($ErrorEvents) {
            Write-Warning "Found Error Events in Directory Service Log:"
            foreach ($Event in $ErrorEvents) {
                Write-Host "  Time: $($Event.TimeCreated)"
                Write-Host "  ID: $($Event.Id)"
                Write-Host "  Description: $($Event.Message.Substring(0, [Math]::Min(100, $Event.Message.Length)))..."
            }
        } else {
            Write-Host "No recent error events found in Directory Service log." -ForegroundColor Green
        }
    } catch {
        Write-Warning "Could not read Event Logs from '$DCName'."
    }

    Write-Host "`n========================================="
    Write-Host "Health check completed for '$DCName'." -ForegroundColor Cyan

} catch {
    Write-Error "A critical error occurred: $($_.Exception.Message)"
}
