Active Directory Replikasyon İçin Kullanılacak Scriptler

Active Directory Replikasyon

Active Directory Replikasyon İçin Kullanılacak Scriptler

  • Test-ADReplicationHealth
  • Remove-LingeringObjects
  • Get-ADReplicationPerformance
  • Get-TombstoneLifetime

# 1. Replikasyon Sağlık Kontrolü ve Raporlama
function Test-ADReplicationHealth {
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[string]$LogPath = “C:\Logs\ADReplication”,
[Parameter(Mandatory = $false)]
[string]$EmailTo = “admin@domain.com”,
[Parameter(Mandatory = $false)]
[int]$WarningThreshold = 45  # minutes
)

Begin {
# Log klasörü oluştur
if (-not (Test-Path $LogPath)) {
New-Item -ItemType Directory -Path $LogPath
}

$timestamp = Get-Date -Format “yyyy-MM-dd_HH-mm”
$logFile = Join-Path $LogPath “ADReplication_$timestamp.log”
$htmlReport = Join-Path $LogPath “ADReplication_$timestamp.html”

# HTML rapor başlığı
$htmlHeader = @”
<style>
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid black; padding: 8px; text-align: left; }
th { background-color: #4CAF50; color: white; }
tr:nth-child(even) { background-color: #f2f2f2; }
.critical { background-color: #ff9999; }
.warning { background-color: #ffeb99; }
</style>
“@
}

Process {
try {
# Tüm Domain Controller’ları al
$DCs = Get-ADDomainController -Filter *
$results = @()

foreach ($DC in $DCs) {
Write-Verbose “Checking replication status for $($DC.HostName)”

# Replikasyon durumunu kontrol et
$replStatus = repadmin /showrepl $DC.HostName /csv | ConvertFrom-Csv

# DC’nin erişilebilirliğini kontrol et
$pingStatus = Test-Connection -ComputerName $DC.HostName -Count 1 -Quiet

# DC servisleri kontrol et
$services = @(“NTDS”, “DNS”, “Netlogon”, “W32Time”)
$serviceStatus = @{}
foreach ($service in $services) {
try {
$status = Get-Service -ComputerName $DC.HostName -Name $service -ErrorAction Stop
$serviceStatus[$service] = $status.Status
}
catch {
$serviceStatus[$service] = “Error”
}
}

# Son replikasyon zamanını al
$lastRepl = ($replStatus | Where-Object { $_.SourceDSA -ne $DC.HostName } |
Measure-Object “Last Success Time” -Maximum).Maximum

$results += [PSCustomObject]@{
DomainController = $DC.HostName
Site            = $DC.Site
IP              = $DC.IPv4Address
Online          = $pingStatus
LastReplication = $lastRepl
NTDSStatus      = $serviceStatus[“NTDS”]
DNSStatus       = $serviceStatus[“DNS”]
NetlogonStatus  = $serviceStatus[“Netlogon”]
TimeStatus      = $serviceStatus[“W32Time”]
FailureCount    = ($replStatus | Where-Object { $_.”Number of Failures” -gt 0 }).Count
}

# Log dosyasına yaz
“$(Get-Date -Format ‘yyyy-MM-dd HH:mm:ss’): Checked $($DC.HostName)” | Out-File $logFile -Append
}

# HTML raporu oluştur
$htmlBody = $results | ConvertTo-Html -Head $htmlHeader -PreContent “<h1>AD Replication Status Report</h1><h3>Generated: $(Get-Date)</h3>”
$htmlBody | Out-File $htmlReport

# Kritik durumları kontrol et ve email gönder
$criticalIssues = $results | Where-Object {
-not $_.Online -or
$_.FailureCount -gt 0 -or
$_.NTDSStatus -ne “Running”
}

if ($criticalIssues) {
$emailBody = “Critical AD Replication Issues Detected:`n`n”
$emailBody += $criticalIssues | Format-Table | Out-String

Send-MailMessage -To $EmailTo `
-Subject “AD Replication Alert: Critical Issues Detected” `
-Body $emailBody `
-BodyAsHtml `
-Attachments $htmlReport
}

return $results
}
catch {
Write-Error “Error occurred: $_”
“$(Get-Date -Format ‘yyyy-MM-dd HH:mm:ss’): ERROR – $_” | Out-File $logFile -Append
}
}
}

# 2. Lingering Object Tespit ve Temizleme
function Remove-LingeringObjects {
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(Mandatory = $true)]
[string]$SourceDC,
[Parameter(Mandatory = $true)]
[string]$TargetDC,
[Parameter(Mandatory = $false)]
[switch]$Advisory,
[Parameter(Mandatory = $false)]
[string]$LogPath = “C:\Logs\LingeringObjects”
)

Begin {
if (-not (Test-Path $LogPath)) {
New-Item -ItemType Directory -Path $LogPath
}

$timestamp = Get-Date -Format “yyyy-MM-dd_HH-mm”
$logFile = Join-Path $LogPath “LingeringObjects_$timestamp.log”
}

Process {
try {
# DC’lerin erişilebilirliğini kontrol et
$sourcePing = Test-Connection -ComputerName $SourceDC -Count 1 -Quiet
$targetPing = Test-Connection -ComputerName $TargetDC -Count 1 -Quiet

if (-not ($sourcePing -and $targetPing)) {
throw “One or both DCs are not reachable”
}

# Target DC’nin GUID’ini al
$targetDCObj = Get-ADDomainController $TargetDC
$targetGuid = $targetDCObj.ObjectGUID

# Naming Context’leri al
$namingContexts = (Get-ADRootDSE -Server $SourceDC).namingContexts

foreach ($nc in $namingContexts) {
“$(Get-Date -Format ‘yyyy-MM-dd HH:mm:ss’): Processing $nc” | Out-File $logFile -Append

if ($Advisory) {
# Advisory mode – sadece raporla
$cmd = “repadmin /removelingeringobjects $SourceDC $targetGuid `”$nc`” /ADVISORY_MODE”
$result = Invoke-Expression $cmd
$result | Out-File $logFile -Append
}
else {
# Gerçek temizlik
if ($PSCmdlet.ShouldProcess($nc, “Remove lingering objects”)) {
$cmd = “repadmin /removelingeringobjects $SourceDC $targetGuid `”$nc`””
$result = Invoke-Expression $cmd
$result | Out-File $logFile -Append
}
}
}

# Sonuçları raporla
Get-Content $logFile
}
catch {
Write-Error “Error occurred: $_”
“$(Get-Date -Format ‘yyyy-MM-dd HH:mm:ss’): ERROR – $_” | Out-File $logFile -Append
}
}
}

# 3. Replikasyon Performans İzleme
function Get-ADReplicationPerformance {
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[int]$SampleInterval = 5,  # seconds
[Parameter(Mandatory = $false)]
[int]$SampleCount = 12,
[Parameter(Mandatory = $false)]
[string]$LogPath = “C:\Logs\ADPerformance”
)

Begin {
if (-not (Test-Path $LogPath)) {
New-Item -ItemType Directory -Path $LogPath
}

$timestamp = Get-Date -Format “yyyy-MM-dd_HH-mm”
$logFile = Join-Path $LogPath “ADPerformance_$timestamp.csv”

$counters = @(
“\DirectoryServices\DS Directory Reads/sec”,
“\DirectoryServices\DS Directory Writes/sec”,
“\DirectoryServices\LDAP Client Sessions”,
“\DirectoryServices\LDAP Bind Time”,
“\DirectoryServices\DRA Pending Replication Operations”,
“\DirectoryServices\DRA Pending Replication Synchronizations”
)
}

Process {
try {
$results = Get-Counter -Counter $counters -SampleInterval $SampleInterval -MaxSamples $SampleCount |
Select-Object -ExpandProperty CounterSamples |
Select-Object Path, CookedValue, TimeStamp

# CSV’ye kaydet
$results | Export-Csv -Path $logFile -NoTypeInformation

# Özet istatistikler hesapla
$summary = $results | Group-Object Path | ForEach-Object {
$values = $_.Group.CookedValue
[PSCustomObject]@{
Counter     = $_.Name
Average    = ($values | Measure-Object -Average).Average
Maximum    = ($values | Measure-Object -Maximum).Maximum
Minimum    = ($values | Measure-Object -Minimum).Minimum
Samples    = $values.Count
}
}

return $summary
}
catch {
Write-Error “Error occurred: $_”
}
}
}

# 4. Tombstone Lifetime İzleme
function Get-TombstoneLifetime {
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[int]$WarningThreshold = 45,  # days
[Parameter(Mandatory = $false)]
[string]$EmailTo = “admin@domain.com”
)

Process {
try {
# Forest yapılandırmasını al
$forest = Get-ADForest
$rootDomain = $forest.RootDomain

# Tombstone Lifetime değerini al
$searchBase = “CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,$((Get-ADDomain $rootDomain).DistinguishedName)”
$tombstoneLifetime = Get-ADObject -SearchBase $searchBase -Filter {objectClass -eq “dSHeuristics”} -Properties tombstoneLifetime

$result = [PSCustomObject]@{
ForestName = $forest.Name
TombstoneLifetime = if ($tombstoneLifetime.tombstoneLifetime) {
[int]$tombstoneLifetime.tombstoneLifetime
} else {
60  # default value
}
Status = “OK”
LastChecked = Get-Date
}

# Warning kontrolü
if ($result.TombstoneLifetime -lt $WarningThreshold) {
$result.Status = “Warning”

# Email uyarısı gönder
$emailBody = @”
Warning: Tombstone Lifetime is set to $($result.TombstoneLifetime) days.
Recommended minimum is $WarningThreshold days.

Forest: $($result.ForestName)
Checked: $($result.LastChecked)
“@

Send-MailMessage -To $EmailTo `
-Subject “AD Tombstone Lifetime Warning” `
-Body $emailBody
}

return $result
}
catch {
Write-Error “Error occurred: $_”
}
}
}

# Kullanım örnekleri:
# 1. Replikasyon sağlık kontrolü
# Test-ADReplicationHealth -Verbose

# 2. Lingering object temizliği (Advisory mode)
# Remove-LingeringObjects -SourceDC “DC1” -TargetDC “DC2” -Advisory

# 3. Performans izleme
# Get-ADReplicationPerformance -SampleInterval 10 -SampleCount 6

# 4. Tombstone lifetime kontrolü
# Get-TombstoneLifetime -WarningThreshold 50

“`

Bu PowerShell scriptleri şunları içerir:

1. **Test-ADReplicationHealth**
– Tüm DC’lerin replikasyon durumunu kontrol eder
– HTML ve log dosyası oluşturur
– Kritik durumlarda email atar
– Servis durumlarını kontrol eder

2. **Remove-LingeringObjects**
– Lingering object tespiti ve temizliği yapar
– Advisory mode desteği
– Detaylı loglama
– Her naming context için ayrı işlem

3. **Get-ADReplicationPerformance**
– Performans sayaçlarını izler
– CSV formatında kayıt tutar
– Özet istatistikler oluşturur
– Çoklu performans metriği desteği

4. **Get-TombstoneLifetime**
– Tombstone lifetime değerini kontrol eder
– Warning threshold kontrolü
– Email uyarı sistemi
– Forest genelinde kontrol

Her script:
– Detaylı hata yakalama
– Loglama
– Email bildirimleri
– Parametrik yapılandırma
özelliklerine sahiptir.

Bu scriptleri kullanarak:
1. Günlük replikasyon kontrolü
2. Haftalık performans raporu
3. Aylık tombstone kontrolü
4. Gerektiğinde lingering object temizliği