Monday 4 September 2023

Get all Domain Replication Report with Email Alert

 Get all Domain Replication Report with Email Alert


# Define email parameters

$EmailParams = @{

    From       = "your@email.com"

    To         = "recipient@email.com"

    Subject    = "Active Directory Replication Health Report"

    SmtpServer = "smtp.example.com"

    Port       = 587

    Credential = (Get-Credential -UserName "yourusername" -Message "Enter your email password")

    UseSsl     = $true

}

 

# Get a list of all domain controllers in the current domain

$DCs = Get-ADDomainController -Filter *

 

# Initialize an empty array to store the report

$ReplicationIssues = @()

 

# Loop through each domain controller and check replication health

foreach ($DC in $DCs) {

    $TargetServer = $DC.Name

    $ReplicationHealth = Get-ADReplicationFailure -Server $TargetServer

 

    # Check if any replication issues were detected on this server

    if ($ReplicationHealth) {

        $EmailBody = @"

        Replication issues detected on server $TargetServer:

 

        $ReplicationHealth

 

        Please investigate and resolve these issues.

 

        Sincerely,

        Your Name

"@

 

        # Add this server's replication issues to the report

        $ReplicationIssues += $EmailBody

    }

}

 

# Check if there were any replication issues across all domain controllers

if ($ReplicationIssues.Count -gt 0) {

    # Generate the email body with the cumulative replication health report

    $EmailBody = @"

    The following replication issues were detected across all domain controllers:

 

    $ReplicationIssues

 

    Please investigate and resolve these issues.

 

    Sincerely,

    Your Name

"@

 

    # Set the email body

    $EmailParams['Body'] = $EmailBody

 

    # Send the email

    Send-MailMessage @EmailParams

}