-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvoke-ADReplicationManager.ps1
More file actions
2254 lines (1867 loc) · 80.6 KB
/
Invoke-ADReplicationManager.ps1
File metadata and controls
2254 lines (1867 loc) · 80.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Requires -Version 5.1
#Requires -Modules ActiveDirectory
# Note: Admin rights recommended for full functionality, but not strictly required for read-only audit mode
<#
.SYNOPSIS
Advanced Active Directory Replication Management Tool with Multi-Mode Operation
.DESCRIPTION
Production-ready AD replication manager with safety guards, parallelism, and comprehensive reporting.
FEATURES:
- Multi-mode operation: Audit | Repair | Verify | AuditRepairVerify
- Scoped execution: Forest | Site | DCList
- WhatIf/Confirm support for all impactful operations
- Parallel DC processing with configurable throttling
- Pipeline-friendly verbose/information streams
- JSON summary for CI/CD integration
- Audit trail with optional transcript logging
- Consolidated reporting (CSV, HTML, JSON)
- Auto-Healing with policy-based repairs and rollback (v3.2)
- Delta Mode for intelligent caching and faster monitoring (v3.3)
.AUTHOR
Adrian Johnson <adrian207@gmail.com>
.VERSION
3.3.0
.DATE
October 28, 2025
.COPYRIGHT
Copyright (c) 2025 Adrian Johnson. All rights reserved.
.LICENSE
MIT License
.NOTES
Optimized for PowerShell 7.5.4+ with enhanced parallel processing and retry logic.
Falls back gracefully to PowerShell 5.1 with serial processing.
Requires: PowerShell 5.1+, RSAT-AD-PowerShell, Domain Admin rights (recommended)
.PARAMETER Mode
Operation mode. Default: Audit
- Audit: Read-only health assessment
- Repair: Audit + repair operations
- Verify: Post-repair verification only
- AuditRepairVerify: Complete workflow
.PARAMETER Scope
Execution scope. Default: DCList
- Forest: All DCs in forest (requires explicit confirmation)
- Site:<Name>: All DCs in specified site
- DCList: Use -DomainControllers parameter
.PARAMETER DomainControllers
Explicit list of DC hostnames. Required when Scope=DCList.
.PARAMETER DomainName
Domain FQDN to query. Default: Current user's domain.
.PARAMETER AutoRepair
Skip repair confirmation prompts. Use with caution.
.PARAMETER Throttle
Max parallel operations. Default: 8. Range: 1-32.
.PARAMETER OutputPath
Report output directory. Default: .\ADRepl-<timestamp>
.PARAMETER AuditTrail
Enable transcript logging for tamper-evident audit trail.
.PARAMETER Timeout
Per-DC operation timeout in seconds. Default: 300.
.EXAMPLE
.\Invoke-ADReplicationManager.ps1 -Mode Audit -DomainControllers DC01,DC02
Audit-only mode for specific DCs (safe, read-only)
.EXAMPLE
.\Invoke-ADReplicationManager.ps1 -Mode Repair -Scope Site:Default-First-Site-Name -AutoRepair -AuditTrail
Automated repair for all DCs in site with full logging
.EXAMPLE
.\Invoke-ADReplicationManager.ps1 -Mode AuditRepairVerify -DomainControllers DC01,DC02 -WhatIf
Preview all actions without executing (WhatIf support)
.EXAMPLE
.\Invoke-ADReplicationManager.ps1 -Mode Audit -Scope Forest -DeltaMode -DeltaThresholdMinutes 120
Delta mode: Only check DCs that had issues in the last 120 minutes (faster monitoring)
.EXAMPLE
.\Invoke-ADReplicationManager.ps1 -Mode Repair -DomainControllers DC01,DC02 -AutoHeal -HealingPolicy Moderate
Auto-healing mode with moderate policy (automatic repairs with safety controls)
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param(
[Parameter(Mandatory = $false)]
[ValidateSet('Audit', 'Repair', 'Verify', 'AuditRepairVerify')]
[string]$Mode = 'Audit',
[Parameter(Mandatory = $false)]
[ValidatePattern('^(Forest|Site:.+|DCList)$')]
[string]$Scope = 'DCList',
[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[string[]]$DomainControllers = @(),
[Parameter(Mandatory = $false)]
[string]$DomainName = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name,
[Parameter(Mandatory = $false)]
[switch]$AutoRepair,
[Parameter(Mandatory = $false)]
[ValidateRange(1, 32)]
[int]$Throttle = 8,
[Parameter(Mandatory = $false)]
[ValidateScript({
if ($_ -and -not (Test-Path (Split-Path $_) -PathType Container)) {
throw "Parent directory must exist: $(Split-Path $_)"
}
$true
})]
[string]$OutputPath = "",
[Parameter(Mandatory = $false)]
[switch]$AuditTrail,
[Parameter(Mandatory = $false)]
[ValidateRange(60, 3600)]
[int]$Timeout = 300,
[Parameter(Mandatory = $false)]
[switch]$FastMode,
# Notification Parameters
[Parameter(Mandatory = $false)]
[string]$SlackWebhook,
[Parameter(Mandatory = $false)]
[string]$TeamsWebhook,
[Parameter(Mandatory = $false)]
[string]$EmailTo,
[Parameter(Mandatory = $false)]
[string]$EmailFrom = "ADReplication@company.com",
[Parameter(Mandatory = $false)]
[string]$SmtpServer,
[Parameter(Mandatory = $false)]
[ValidateSet('OnError', 'OnIssues', 'Always', 'Never')]
[string]$EmailNotification = 'OnIssues',
# Scheduled Task Parameters
[Parameter(Mandatory = $false)]
[switch]$CreateScheduledTask,
[Parameter(Mandatory = $false)]
[ValidateSet('Hourly', 'Every4Hours', 'Daily', 'Weekly')]
[string]$TaskSchedule = 'Daily',
[Parameter(Mandatory = $false)]
[string]$TaskName = "AD Replication Health Check",
[Parameter(Mandatory = $false)]
[string]$TaskTime = "02:00",
# Health Score Parameters
[Parameter(Mandatory = $false)]
[switch]$EnableHealthScore,
[Parameter(Mandatory = $false)]
[string]$HealthHistoryPath = "$env:ProgramData\ADReplicationManager\History",
# Auto-Healing Parameters
[Parameter(Mandatory = $false)]
[switch]$AutoHeal,
[Parameter(Mandatory = $false)]
[ValidateSet('Conservative', 'Moderate', 'Aggressive')]
[string]$HealingPolicy = 'Conservative',
[Parameter(Mandatory = $false)]
[ValidateRange(1, 100)]
[int]$MaxHealingActions = 10,
[Parameter(Mandatory = $false)]
[switch]$EnableRollback,
[Parameter(Mandatory = $false)]
[string]$HealingHistoryPath = "$env:ProgramData\ADReplicationManager\Healing",
[Parameter(Mandatory = $false)]
[ValidateRange(1, 60)]
[int]$HealingCooldownMinutes = 15,
# Delta Mode Parameters
[Parameter(Mandatory = $false)]
[switch]$DeltaMode,
[Parameter(Mandatory = $false)]
[ValidateRange(1, 1440)]
[int]$DeltaThresholdMinutes = 60,
[Parameter(Mandatory = $false)]
[string]$DeltaCachePath = "$env:ProgramData\ADReplicationManager\Cache",
[Parameter(Mandatory = $false)]
[switch]$ForceFull
)
# ============================================================================
# SCHEDULED TASK CREATION (Exit Early)
# ============================================================================
if ($CreateScheduledTask) {
Write-Information "Creating scheduled task: $TaskName" -InformationAction Continue
# Build the command arguments
$scriptPath = $PSCommandPath
$arguments = "-NoProfile -ExecutionPolicy Bypass -File `"$scriptPath`" -Mode $Mode -Scope $Scope"
if ($DomainControllers.Count -gt 0) {
$dcList = $DomainControllers -join ','
$arguments += " -DomainControllers $dcList"
}
if ($FastMode) { $arguments += " -FastMode" }
if ($AutoRepair) { $arguments += " -AutoRepair" }
if ($AuditTrail) { $arguments += " -AuditTrail" }
if ($EnableHealthScore) { $arguments += " -EnableHealthScore" }
if ($Throttle -ne 8) { $arguments += " -Throttle $Throttle" }
if ($OutputPath) { $arguments += " -OutputPath `"$OutputPath`"" }
if ($SlackWebhook) { $arguments += " -SlackWebhook `"$SlackWebhook`"" }
if ($TeamsWebhook) { $arguments += " -TeamsWebhook `"$TeamsWebhook`"" }
if ($EmailTo) {
$arguments += " -EmailTo `"$EmailTo`""
if ($SmtpServer) { $arguments += " -SmtpServer `"$SmtpServer`"" }
if ($EmailFrom) { $arguments += " -EmailFrom `"$EmailFrom`"" }
$arguments += " -EmailNotification $EmailNotification"
}
try {
# Create the action
$action = New-ScheduledTaskAction -Execute "pwsh.exe" -Argument $arguments
# Create the trigger based on schedule
$trigger = switch ($TaskSchedule) {
'Hourly' {
New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval (New-TimeSpan -Hours 1) -RepetitionDuration ([TimeSpan]::MaxValue)
}
'Every4Hours' {
New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval (New-TimeSpan -Hours 4) -RepetitionDuration ([TimeSpan]::MaxValue)
}
'Daily' {
New-ScheduledTaskTrigger -Daily -At $TaskTime
}
'Weekly' {
New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday -At $TaskTime
}
}
# Create the principal (run as SYSTEM with highest privileges)
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
# Register the task
[void](Register-ScheduledTask -TaskName $TaskName `
-Action $action `
-Trigger $trigger `
-Principal $principal `
-Description "Automated AD replication health monitoring and repair" `
-Force)
Write-Information "✅ Scheduled task created successfully!" -InformationAction Continue
Write-Information " Task Name: $TaskName" -InformationAction Continue
Write-Information " Schedule: $TaskSchedule" -InformationAction Continue
Write-Information " Command: pwsh.exe $arguments" -InformationAction Continue
Write-Information "" -InformationAction Continue
Write-Information "To manage the task:" -InformationAction Continue
Write-Information " View: Get-ScheduledTask -TaskName '$TaskName'" -InformationAction Continue
Write-Information " Run: Start-ScheduledTask -TaskName '$TaskName'" -InformationAction Continue
Write-Information " Remove: Unregister-ScheduledTask -TaskName '$TaskName' -Confirm:`$false" -InformationAction Continue
exit 0
}
catch {
Write-Error "Failed to create scheduled task: $_"
exit 1
}
}
# ============================================================================
# GLOBAL STATE
# ============================================================================
$Script:RepairLog = [System.Collections.ArrayList]::Synchronized((New-Object System.Collections.ArrayList))
$Script:StartTime = Get-Date
$Script:ExitCode = 0
# Retry configuration
$Script:MaxRetryAttempts = 3
$Script:InitialDelaySeconds = 2
$Script:MaxDelaySeconds = 30
$Script:TransientErrorPatterns = @(
'RPC server is unavailable',
'network path was not found',
'connection attempt failed',
'timeout',
'server is not operational',
'temporarily unavailable'
)
# Fast Mode optimizations
if ($FastMode) {
Write-Information "⚡ Fast Mode enabled - Performance optimizations active" -InformationAction Continue
# Increase throttle for faster parallel execution
if ($Throttle -eq 8) {
$Throttle = 24
Write-Information " → Throttle increased: 8 → 24" -InformationAction Continue
}
# Reduce verification wait time
$Script:VerificationWaitSeconds = 30
# Reduce retry attempts for faster failure
$Script:MaxRetryAttempts = 2
$Script:InitialDelaySeconds = 1
Write-Information " → Verification wait reduced: 120s → 30s" -InformationAction Continue
Write-Information " → Retry attempts reduced: 3 → 2" -InformationAction Continue
Write-Information " → Expected 40-60% performance improvement" -InformationAction Continue
}
# ============================================================================
# HELPER FUNCTIONS
# ============================================================================
function Write-RepairLog {
<#
.SYNOPSIS
Pipeline-friendly logging with structured output streams.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Message,
[Parameter(Mandatory = $false)]
[ValidateSet('Verbose', 'Information', 'Warning', 'Error')]
[string]$Level = 'Information'
)
$timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
$logEntry = "[$timestamp] [$Level] $Message"
[void]$Script:RepairLog.Add($logEntry)
switch ($Level) {
'Verbose' { Write-Verbose $Message }
'Information' { Write-Information $Message -InformationAction Continue }
'Warning' { Write-Warning $Message }
'Error' { Write-Error $Message }
}
}
function Invoke-WithRetry {
<#
.SYNOPSIS
Executes a script block with exponential backoff retry logic.
.DESCRIPTION
Retries transient failures with exponential backoff.
Non-transient errors (auth, permissions) fail immediately without retry.
Backoff formula: delay = min(InitialDelay * 2^attempt, MaxDelay)
Example: 2s, 4s, 8s, 16s, 30s (capped at MaxDelay)
.PARAMETER ScriptBlock
The script block to execute
.PARAMETER MaxAttempts
Maximum number of attempts (default: 3)
.PARAMETER Context
Descriptive context for logging (e.g., "Query DC01")
.EXAMPLE
Invoke-WithRetry -ScriptBlock { Get-ADReplicationPartnerMetadata -Target $dc } -Context "Query $dc"
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[scriptblock]$ScriptBlock,
[Parameter(Mandatory = $false)]
[int]$MaxAttempts = $Script:MaxRetryAttempts,
[Parameter(Mandatory = $false)]
[string]$Context = "Operation"
)
$attempt = 0
$lastError = $null
while ($attempt -lt $MaxAttempts) {
$attempt++
try {
Write-RepairLog "$Context - Attempt $attempt/$MaxAttempts" -Level Verbose
# Execute the script block
$result = & $ScriptBlock
# Success - return result
if ($attempt -gt 1) {
Write-RepairLog "$Context - Succeeded on attempt $attempt" -Level Information
}
return $result
}
catch {
$lastError = $_
$errorMessage = $_.Exception.Message
# Check if error is transient
$isTransient = $false
foreach ($pattern in $Script:TransientErrorPatterns) {
if ($errorMessage -match $pattern) {
$isTransient = $true
break
}
}
# Check for permanent errors (don't retry)
$isPermanent = $errorMessage -match '(Access is denied|Logon failure|domain does not exist|cannot find|not found)'
if ($isPermanent) {
Write-RepairLog "$Context - Permanent error detected, not retrying: $errorMessage" -Level Warning
throw
}
if (-not $isTransient) {
Write-RepairLog "$Context - Non-transient error, not retrying: $errorMessage" -Level Warning
throw
}
# Transient error - calculate backoff and retry
if ($attempt -lt $MaxAttempts) {
# Exponential backoff: 2s, 4s, 8s, 16s, 30s (capped)
$delay = [Math]::Min(
$Script:InitialDelaySeconds * [Math]::Pow(2, $attempt - 1),
$Script:MaxDelaySeconds
)
Write-RepairLog "$Context - Transient error on attempt $attempt/$MaxAttempts, retrying in $delay seconds: $errorMessage" -Level Warning
Start-Sleep -Seconds $delay
}
else {
Write-RepairLog "$Context - Failed after $MaxAttempts attempts: $errorMessage" -Level Error
throw
}
}
}
# Should never reach here, but just in case
if ($lastError) {
throw $lastError
}
}
function Send-SlackAlert {
<#
.SYNOPSIS
Sends a formatted alert to Slack webhook.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[hashtable]$Summary,
[Parameter(Mandatory = $true)]
[string]$WebhookUrl
)
try {
# Determine color based on exit code
$color = switch ($Script:ExitCode) {
0 { "good" } # Green
2 { "warning" } # Yellow
default { "danger" } # Red
}
# Determine emoji status
$statusEmoji = switch ($Script:ExitCode) {
0 { ":white_check_mark:" }
2 { ":warning:" }
3 { ":no_entry:" }
default { ":x:" }
}
$statusText = switch ($Script:ExitCode) {
0 { "Healthy" }
2 { "Issues Detected" }
3 { "DCs Unreachable" }
default { "Error" }
}
# Build Slack payload
$payload = @{
username = "AD Replication Monitor"
icon_emoji = ":satellite:"
attachments = @(
@{
color = $color
title = "$statusEmoji AD Replication Report - $statusText"
fields = @(
@{ title = "Mode"; value = $Summary.Mode; short = $true }
@{ title = "Exit Code"; value = $Script:ExitCode; short = $true }
@{ title = "Total DCs"; value = $Summary.TotalDCs; short = $true }
@{ title = "Healthy"; value = "$($Summary.HealthyDCs) :white_check_mark:"; short = $true }
@{ title = "Degraded"; value = "$($Summary.DegradedDCs) :warning:"; short = $true }
@{ title = "Unreachable"; value = "$($Summary.UnreachableDCs) :no_entry:"; short = $true }
@{ title = "Issues Found"; value = $Summary.IssuesFound; short = $true }
@{ title = "Actions Performed"; value = $Summary.ActionsPerformed; short = $true }
@{ title = "Duration"; value = $Summary.ExecutionTime; short = $true }
@{ title = "Domain"; value = $Summary.Domain; short = $true }
)
footer = "AD Replication Manager"
ts = [int][double]::Parse((Get-Date -UFormat %s))
}
)
} | ConvertTo-Json -Depth 5
Invoke-RestMethod -Uri $WebhookUrl -Method Post -Body $payload -ContentType 'application/json' -ErrorAction Stop
Write-RepairLog "Slack notification sent successfully" -Level Verbose
}
catch {
Write-RepairLog "Failed to send Slack notification: $_" -Level Warning
}
}
function Send-TeamsAlert {
<#
.SYNOPSIS
Sends a formatted alert to Microsoft Teams webhook.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[hashtable]$Summary,
[Parameter(Mandatory = $true)]
[string]$WebhookUrl
)
try {
# Determine theme color based on exit code
$themeColor = switch ($Script:ExitCode) {
0 { "00FF00" } # Green
2 { "FFA500" } # Orange
3 { "FF4500" } # Red-Orange
default { "FF0000" } # Red
}
$statusText = switch ($Script:ExitCode) {
0 { "✅ Healthy" }
2 { "⚠️ Issues Detected" }
3 { "🚫 DCs Unreachable" }
default { "❌ Error" }
}
# Build Teams adaptive card payload
$payload = @{
"@type" = "MessageCard"
"@context" = "https://schema.org/extensions"
summary = "AD Replication Report"
themeColor = $themeColor
title = "AD Replication Report - $statusText"
sections = @(
@{
activityTitle = "**$($Summary.Mode)** Mode Execution"
activitySubtitle = "Domain: $($Summary.Domain)"
facts = @(
@{ name = "Exit Code"; value = $Script:ExitCode }
@{ name = "Total DCs"; value = $Summary.TotalDCs }
@{ name = "Healthy"; value = "$($Summary.HealthyDCs) ✅" }
@{ name = "Degraded"; value = "$($Summary.DegradedDCs) ⚠️" }
@{ name = "Unreachable"; value = "$($Summary.UnreachableDCs) 🚫" }
@{ name = "Issues Found"; value = $Summary.IssuesFound }
@{ name = "Actions Performed"; value = $Summary.ActionsPerformed }
@{ name = "Duration"; value = $Summary.ExecutionTime }
)
}
)
} | ConvertTo-Json -Depth 5
Invoke-RestMethod -Uri $WebhookUrl -Method Post -Body $payload -ContentType 'application/json; charset=utf-8' -ErrorAction Stop
Write-RepairLog "Teams notification sent successfully" -Level Verbose
}
catch {
Write-RepairLog "Failed to send Teams notification: $_" -Level Warning
}
}
function Send-EmailAlert {
<#
.SYNOPSIS
Sends an email alert with replication summary.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[hashtable]$Summary,
[Parameter(Mandatory = $true)]
[string]$To,
[Parameter(Mandatory = $true)]
[string]$From,
[Parameter(Mandatory = $true)]
[string]$SmtpServer
)
try {
$statusText = switch ($Script:ExitCode) {
0 { "✅ Healthy" }
2 { "⚠️ Issues Detected" }
3 { "🚫 DCs Unreachable" }
default { "❌ Error" }
}
$priority = switch ($Script:ExitCode) {
0 { "Normal" }
2 { "High" }
default { "High" }
}
$subject = "AD Replication Alert - $statusText ($($Summary.DegradedDCs) Degraded, $($Summary.UnreachableDCs) Unreachable)"
$body = @"
AD Replication Manager - Execution Report
==========================================
Status: $statusText
Exit Code: $($Script:ExitCode)
SUMMARY
-------
Mode: $($Summary.Mode)
Domain: $($Summary.Domain)
Execution Time: $($Summary.ExecutionTime)
DOMAIN CONTROLLER STATUS
------------------------
Total DCs: $($Summary.TotalDCs)
Healthy: $($Summary.HealthyDCs) ✅
Degraded: $($Summary.DegradedDCs) ⚠️
Unreachable: $($Summary.UnreachableDCs) 🚫
ACTIONS
-------
Issues Found: $($Summary.IssuesFound)
Actions Performed: $($Summary.ActionsPerformed)
REPORTS
-------
Output Directory: $($Summary.OutputPath)
---
This is an automated message from AD Replication Manager
Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
"@
$mailParams = @{
To = $To
From = $From
Subject = $subject
Body = $body
SmtpServer = $SmtpServer
Priority = $priority
}
Send-MailMessage @mailParams -ErrorAction Stop
Write-RepairLog "Email notification sent to $To" -Level Verbose
}
catch {
Write-RepairLog "Failed to send email notification: $_" -Level Warning
}
}
function Get-HealthScore {
<#
.SYNOPSIS
Calculates a 0-100 health score based on DC status and replication health.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[array]$Snapshots,
[Parameter(Mandatory = $true)]
[array]$Issues
)
# Start with perfect score
$score = 100.0
# Deduct points for DC status
foreach ($snapshot in $Snapshots) {
switch ($snapshot.Status) {
'Unreachable' {
$score -= 10 # Major penalty for unreachable DCs
}
'Degraded' {
$score -= 5 # Medium penalty for degraded DCs
}
}
}
# Deduct points for issues
foreach ($issue in $Issues) {
switch ($issue.Severity) {
'Critical' { $score -= 3 }
'High' { $score -= 2 }
'Medium' { $score -= 1 }
'Low' { $score -= 0.5 }
}
}
# Deduct for stale replication (if data available)
foreach ($snapshot in $Snapshots) {
if ($snapshot.InboundPartners) {
foreach ($partner in $snapshot.InboundPartners) {
if ($partner.LastReplicationSuccess) {
$hoursSinceSuccess = ((Get-Date) - [datetime]$partner.LastReplicationSuccess).TotalHours
if ($hoursSinceSuccess -gt 48) {
$score -= 2 # Very stale
}
elseif ($hoursSinceSuccess -gt 24) {
$score -= 1 # Stale
}
}
}
}
}
# Ensure score stays within 0-100 range
$score = [Math]::Max(0, [Math]::Min(100, $score))
# Determine letter grade
$grade = switch ($score) {
{$_ -ge 95} { "A+ - Excellent" }
{$_ -ge 90} { "A - Excellent" }
{$_ -ge 85} { "B+ - Very Good" }
{$_ -ge 80} { "B - Good" }
{$_ -ge 75} { "C+ - Fair" }
{$_ -ge 70} { "C - Fair" }
{$_ -ge 60} { "D - Poor" }
default { "F - Critical" }
}
return @{
Score = [Math]::Round($score, 2)
Grade = $grade
Timestamp = Get-Date
}
}
function Save-HealthHistory {
<#
.SYNOPSIS
Saves health score to historical CSV file for trend analysis.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[hashtable]$HealthScore,
[Parameter(Mandatory = $true)]
[hashtable]$Summary,
[Parameter(Mandatory = $true)]
[string]$HistoryPath
)
try {
# Ensure directory exists
if (-not (Test-Path $HistoryPath)) {
New-Item -Path $HistoryPath -ItemType Directory -Force | Out-Null
}
$historyFile = Join-Path $HistoryPath "health-history.csv"
# Create history record
$record = [PSCustomObject]@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
HealthScore = $HealthScore.Score
Grade = $HealthScore.Grade
TotalDCs = $Summary.TotalDCs
HealthyDCs = $Summary.HealthyDCs
DegradedDCs = $Summary.DegradedDCs
UnreachableDCs = $Summary.UnreachableDCs
IssuesFound = $Summary.IssuesFound
ActionsPerformed = $Summary.ActionsPerformed
Mode = $Summary.Mode
ExitCode = $Script:ExitCode
}
# Append to CSV (create with headers if doesn't exist)
if (Test-Path $historyFile) {
$record | Export-Csv $historyFile -Append -NoTypeInformation
}
else {
$record | Export-Csv $historyFile -NoTypeInformation
}
Write-RepairLog "Health history saved to: $historyFile" -Level Verbose
# Also save a snapshot in JSON format for richer analysis
$snapshotFile = Join-Path $HistoryPath "snapshot-$(Get-Date -Format 'yyyyMMdd-HHmmss').json"
@{
HealthScore = $HealthScore
Summary = $Summary
Timestamp = Get-Date -Format 'o'
} | ConvertTo-Json -Depth 3 | Out-File $snapshotFile
# Keep only last 90 days of snapshots to prevent bloat
Get-ChildItem $HistoryPath -Filter "snapshot-*.json" |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-90) } |
Remove-Item -Force
Write-RepairLog "Health snapshot saved to: $snapshotFile" -Level Verbose
}
catch {
Write-RepairLog "Failed to save health history: $_" -Level Warning
}
}
function Resolve-ScopeToDCs {
<#
.SYNOPSIS
Resolves Scope parameter to explicit DC list with safety checks.
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[string]$Scope,
[string[]]$ExplicitDCs,
[string]$Domain
)
$resolvedDCs = @()
switch -Regex ($Scope) {
'^Forest$' {
Write-RepairLog "Resolving Forest scope - this targets ALL domain controllers" -Level Warning
if (-not $PSCmdlet.ShouldProcess("All DCs in forest", "Query and process")) {
throw "Forest scope requires explicit confirmation. Operation cancelled."
}
try {
$forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
foreach ($domain in $forest.Domains) {
$dcs = Get-ADDomainController -Filter * -Server $domain.Name -ErrorAction Stop
$resolvedDCs += $dcs | Select-Object -ExpandProperty HostName
}
Write-RepairLog "Resolved $($resolvedDCs.Count) DCs across forest" -Level Information
}
catch {
throw "Failed to resolve forest DCs: $_"
}
}
'^Site:(.+)$' {
$siteName = $Matches[1]
Write-RepairLog "Resolving Site scope: $siteName" -Level Information
try {
$dcs = Get-ADDomainController -Filter "Site -eq '$siteName'" -Server $Domain -ErrorAction Stop
$resolvedDCs = $dcs | Select-Object -ExpandProperty HostName
if ($resolvedDCs.Count -eq 0) {
throw "No DCs found in site '$siteName'. Verify site name."
}
Write-RepairLog "Resolved $($resolvedDCs.Count) DCs in site $siteName" -Level Information
}
catch {
throw "Failed to resolve site '$siteName': $_"
}
}
'^DCList$' {
if ($ExplicitDCs.Count -eq 0) {
throw "Scope=DCList requires -DomainControllers parameter. Use -Scope Forest or -Scope Site:<name> for discovery."
}
# Handle comma-separated single string
if ($ExplicitDCs.Count -eq 1 -and $ExplicitDCs[0] -match ',') {
$ExplicitDCs = $ExplicitDCs[0] -split ',' | ForEach-Object { $_.Trim() }
}
$resolvedDCs = $ExplicitDCs
Write-RepairLog "Using explicit DC list: $($resolvedDCs -join ', ')" -Level Information
}
}
if ($resolvedDCs.Count -eq 0) {
throw "No domain controllers resolved. Check parameters and try again."
}
return $resolvedDCs
}
function Get-ReplicationSnapshot {
<#
.SYNOPSIS
Captures current replication state across DCs with parallel processing.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string[]]$DomainControllers,
[Parameter(Mandatory = $false)]
[int]$ThrottleLimit = 8,
[Parameter(Mandatory = $false)]
[int]$TimeoutSeconds = 300
)
Write-RepairLog "Capturing replication snapshot for $($DomainControllers.Count) DCs (throttle: $ThrottleLimit)" -Level Information
$results = [System.Collections.Concurrent.ConcurrentBag[object]]::new()
# PowerShell 7+ parallel support
if ($PSVersionTable.PSVersion.Major -ge 7) {
$DomainControllers | ForEach-Object -Parallel {
$dc = $_
$timeout = $using:TimeoutSeconds
$snapshot = [PSCustomObject]@{
DC = $dc
Timestamp = Get-Date
InboundPartners = @()
Failures = @()
Status = 'Unknown'
Error = $null
}
try {
# Time-bounded operation
$job = Start-Job -ScriptBlock {
param($dcName)
Import-Module ActiveDirectory -ErrorAction Stop
$partners = Get-ADReplicationPartnerMetadata -Target $dcName -ErrorAction Stop
$failures = Get-ADReplicationFailure -Target $dcName -ErrorAction SilentlyContinue
return @{
Partners = $partners
Failures = $failures
}
} -ArgumentList $dc
$completed = Wait-Job -Job $job -Timeout $timeout
if ($completed) {
$data = Receive-Job -Job $job -ErrorAction Stop
$snapshot.InboundPartners = $data.Partners | ForEach-Object {
[PSCustomObject]@{
Partner = $_.Partner
Partition = $_.Partition
LastAttempt = $_.LastReplicationAttempt
LastSuccess = $_.LastReplicationSuccess
LastResult = $_.LastReplicationResult
ConsecutiveFailures = $_.ConsecutiveReplicationFailures
HoursSinceLastSuccess = if ($_.LastReplicationSuccess) {
((Get-Date) - $_.LastReplicationSuccess).TotalHours
} else { $null }
}
}