-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGet-HVReplicaReport.ps1
More file actions
844 lines (701 loc) · 28.5 KB
/
Copy pathGet-HVReplicaReport.ps1
File metadata and controls
844 lines (701 loc) · 28.5 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
#Requires -Version 7.0
#Requires -Modules Hyper-V
<#
.SYNOPSIS
Generates an HTML report of Hyper-V VM replication status and settings across multiple hosts.
.DESCRIPTION
This script collects replication information from multiple Hyper-V hosts, compares VM settings
between primary and replica VMs, and generates a comprehensive HTML report with visual indicators
for replication health and settings mismatches.
.PARAMETER ReportFilePath
Path where the HTML report will be saved. Default: c:\temp\ReplicaReport.html
.PARAMETER MaxReportAgeInMinutes
Age threshold in minutes for report staleness warning. Default: 60
.PARAMETER SkipSettingsCheck
Skip the VM settings comparison between primary and replica VMs.
.PARAMETER ThrottleLimit
Controls how many Hyper-V hosts are queried in parallel. Must be between 1 and [int]::MaxValue. Default: 4.
.PARAMETER DisableAlerts
Suppresses alerts when the report is stale or critical issues are detected.
#>
param (
[string]$ReportFilePath = 'c:\temp\ReplicaReport.html',
[int]$MaxReportAgeInMinutes = 60,
[switch]$SkipSettingsCheck,
[ValidateRange(1, [int]::MaxValue)]
[int]$ThrottleLimit = 4,
[switch]$DisableAlerts
)
# Set global variable for alerting based on parameter
$script:AlertsEnabled = -not $DisableAlerts.IsPresent
#region Function Definitions
function Get-WrappedMessage {
<#
.SYNOPSIS
Wraps a plain-text message in an alert-style HTML template.
.PARAMETER Message
Plain-text message to include in the alert body.
.PARAMETER Title
Alert title displayed in the header area.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Message,
[string]$Title = 'Alert'
)
$encodedMessage = $Message -replace '&', '&'
$encodedMessage = $encodedMessage -replace '<', '<'
$encodedMessage = $encodedMessage -replace '>', '>'
$formattedMessage = $encodedMessage -replace "(`r`n|`n|`r)", '<br />'
return @"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
body {
margin: 0;
padding: 0;
background-color: #f5f6f8;
font-family: 'Segoe UI', Tahoma, Arial, sans-serif;
color: #1f2933;
}
.alert-wrapper {
width: 100%;
padding: 24px;
box-sizing: border-box;
}
.alert-card {
max-width: 720px;
margin: 0 auto;
background-color: #ffffff;
border: 1px solid #e5e7eb;
border-left: 6px solid #d64545;
border-radius: 8px;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
}
.alert-header {
padding: 18px 22px;
background-color: #fff5f5;
border-bottom: 1px solid #f2dede;
font-size: 18px;
font-weight: 700;
color: #b91c1c;
}
.alert-body {
padding: 20px 22px 24px 22px;
font-size: 14px;
line-height: 1.6;
}
.alert-footer {
padding: 14px 22px 18px 22px;
font-size: 12px;
color: #6b7280;
border-top: 1px solid #f3f4f6;
}
.alert-kicker {
text-transform: uppercase;
letter-spacing: 0.08em;
font-size: 11px;
font-weight: 700;
color: #9b1c1c;
margin-bottom: 6px;
}
</style>
</head>
<body>
<div class="alert-wrapper">
<div class="alert-card">
<div class="alert-header">$Title</div>
<div class="alert-body">
<div class="alert-kicker">Attention Required</div>
<div>$formattedMessage</div>
</div>
<div class="alert-footer">Generated by Hyper-V Replica Reporter</div>
</div>
</div>
</body>
</html>
"@
}
function Test-VMSettingsEqual {
<#
.SYNOPSIS
Compares two pre-collected VM settings objects for equality.
.DESCRIPTION
Takes two settings objects (already gathered) and compares them by converting
to JSON and checking for differences. More efficient than Test-VMReplicaSettingsMatch
when settings are already cached.
.PARAMETER PrimarySettings
Settings object for the primary VM
.PARAMETER ReplicaSettings
Settings object for the replica VM
.OUTPUTS
Boolean - True if settings match, False if they differ
#>
param (
[Parameter(Mandatory = $true)]
[psobject]$PrimarySettings,
[Parameter(Mandatory = $true)]
[psobject]$ReplicaSettings
)
# Remove host-specific fields so only VM configuration is compared
$primaryComparable = $PrimarySettings | Select-Object -Property * -ExcludeProperty HostName
$replicaComparable = $ReplicaSettings | Select-Object -Property * -ExcludeProperty HostName
# Convert both settings objects to JSON for comparison
# Use a consistent depth so nested properties (e.g. SCSI controllers) are fully captured
$primaryJson = $primaryComparable | ConvertTo-Json -Depth 10
$replicaJson = $replicaComparable | ConvertTo-Json -Depth 10
$settingsMatch = $primaryJson -eq $replicaJson
if ($script:AlertsEnabled -and -not $settingsMatch) {
$message = @"
A mismatch in VM settings has been detected between a primary and replica VM. This may indicate a configuration drift issue that could impact replication health. Please review the report for details on the affected VM and investigate further.
"@
$htmlMessage = Get-WrappedMessage -Message $message
Send-ReplicaReportAlert -Subject 'Hyper-V Replica Reporter Alert: VM Settings Mismatch Detected' -Message $htmlMessage
}
# Return true only when the serialized representations are identical
return $settingsMatch
}
function Get-HostLookupAliases {
<#
.SYNOPSIS
Builds equivalent host names for cache lookups.
.DESCRIPTION
Hyper-V replication relationships can store either a short host name or an FQDN
for PrimaryServer and ReplicaServer. The settings cache is populated from the
configured host list, so cache lookups need to tolerate either form.
.PARAMETER HostName
Host name from the replication relationship or settings cache.
.OUTPUTS
String array containing normalized FQDN/original and short-name aliases.
#>
param (
[AllowNull()]
[string]$HostName
)
if ([string]::IsNullOrWhiteSpace($HostName)) {
return @()
}
$normalizedHostName = $HostName.Trim().TrimEnd('.')
$shortHostName = ($normalizedHostName -split '\.')[0]
return @($normalizedHostName, $shortHostName) |
Where-Object { ![string]::IsNullOrWhiteSpace($_) } |
Select-Object -Unique
}
function New-VMSettingsLookupKey {
<#
.SYNOPSIS
Builds the composite key used for VM settings lookups.
#>
param (
[Parameter(Mandatory = $true)]
[string]$HostName,
[Parameter(Mandatory = $true)]
[string]$VMName
)
return '{0}|{1}' -f $HostName, $VMName
}
function Add-VMSettingsLookupEntry {
<#
.SYNOPSIS
Adds a VM settings object to the lookup table by all supported host aliases.
#>
param (
[Parameter(Mandatory = $true)]
[hashtable]$Lookup,
[Parameter(Mandatory = $true)]
[psobject]$SettingsRow
)
foreach ($hostAlias in (Get-HostLookupAliases -HostName $SettingsRow.HostName)) {
$key = New-VMSettingsLookupKey -HostName $hostAlias -VMName $SettingsRow.VMName
if ($Lookup.ContainsKey($key) -and $Lookup[$key].HostName -ne $SettingsRow.HostName) {
Write-Warning ('Duplicate VM settings cache key {0} found for hosts {1} and {2}; keeping the first entry.' -f $key, $Lookup[$key].HostName, $SettingsRow.HostName)
continue
}
$Lookup[$key] = $SettingsRow
}
}
function Get-VMSettingsFromLookup {
<#
.SYNOPSIS
Retrieves VM settings using exact, FQDN, or short host-name forms.
#>
param (
[Parameter(Mandatory = $true)]
[hashtable]$Lookup,
[Parameter(Mandatory = $true)]
[string]$HostName,
[Parameter(Mandatory = $true)]
[string]$VMName
)
foreach ($hostAlias in (Get-HostLookupAliases -HostName $HostName)) {
$key = New-VMSettingsLookupKey -HostName $hostAlias -VMName $VMName
if ($Lookup.ContainsKey($key)) {
return $Lookup[$key]
}
}
return $null
}
function Get-HostReplicationAndSettings {
<#
.SYNOPSIS
Retrieves replication status and VM settings from a single Hyper-V host.
.DESCRIPTION
Connects to a Hyper-V host, retrieves all VM replication information (excluding Extended replicas),
and collects detailed settings for each replicated VM. Designed to run in parallel across multiple hosts.
.PARAMETER HostName
Name of the Hyper-V host to query
.OUTPUTS
PSCustomObject containing HostName, ReplicationInfo array, and VmSettings array
#>
param (
[Parameter(Mandatory = $true)]
[string]$HostName
)
# Nested helper function to build a normalized VM settings object
function New-VMSettingsObject {
<#
.SYNOPSIS
Creates a standardized settings object for a VM.
.DESCRIPTION
Gathers memory, CPU, storage, and SCSI controller information
for a VM and packages it into a consistent format for comparison.
#>
param (
[Parameter(Mandatory = $true)]
[Microsoft.HyperV.PowerShell.VirtualMachine]$VM,
[Parameter(Mandatory = $true)]
[string]$CurrentHost
)
# Collect VM resource information
$vmMemory = Get-VMMemory -VM $VM
$vmCPU = Get-VMProcessor -VM $VM
$vmHardDrives = Get-VHD -VMId $VM.VMId -ComputerName $CurrentHost | Sort-Object -Property Path
$vmSCSIControllers = Get-VMScsiController -VM $VM | Sort-Object -Property Name
# Normalize drive/controller data to avoid host-specific differences
$normalizedHardDriveSizes = $vmHardDrives | ForEach-Object { $_.Size }
$normalizedScsiControllers = $vmSCSIControllers | ForEach-Object {
[pscustomobject]@{
Name = $_.Name
DriveCount = ($_.Drives).Count
}
}
# Return standardized settings object
return [pscustomobject]@{
HostName = $CurrentHost
VMName = $VM.Name
MemoryStartup = $vmMemory.Startup
MemoryMinimum = $vmMemory.Minimum
MemoryMaximum = $vmMemory.Maximum
CPUCount = $vmCPU.Count
HardDriveCount = $vmHardDrives.Count
HardDriveSize = $normalizedHardDriveSizes
SCSIControllers = $normalizedScsiControllers
}
}
# Initialize result containers
$hostReplication = @()
$hostSettings = @()
try {
# Retrieve all replication relationships (excluding Extended replicas)
$hostReplication = Get-VMReplication -ComputerName $HostName -ErrorAction Stop |
Where-Object { $_.RelationshipType -ne 'Extended' }
# Get unique list of VMs involved in replication
$vmNamesOnHost = $hostReplication | Select-Object -ExpandProperty Name -Unique
# Collect detailed settings for each replicated VM
foreach ($vmName in $vmNamesOnHost) {
try {
$vm = Get-VM -ComputerName $HostName -Name $vmName -ErrorAction Stop
$hostSettings += New-VMSettingsObject -VM $vm -CurrentHost $HostName
}
catch {
Write-Warning ("[{0}] Failed to gather settings for VM '{1}': {2}" -f $HostName, $vmName, $_.Exception.Message)
}
}
}
catch {
Write-Warning ("[{0}] Failed to retrieve replication data: {1}" -f $HostName, $_.Exception.Message)
}
# Return combined host data
return [pscustomobject]@{
HostName = $HostName
ReplicationInfo = $hostReplication
VmSettings = $hostSettings
}
}
function Send-ReplicaReportAlert {
<#
.SYNOPSIS
Sends an email alerts for the Hyper-V replica reporter, such as when a report is stale or a critical issue is detected.
.PARAMETER To
Recipient email addresses. Default: ITStaff@mainstreetcu.ca
.PARAMETER From
Sender email addresses. Default: hvReplicaReporter@mainstreetcu.ca
.PARAMETER Message
Email message body (can include HTML content).
.PARAMETER Subject
Email subject line. Default: 'Hyper-V Replica Reporter Alert'
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Message,
[string]$Subject = 'Hyper-V Replica Reporter Alert',
[string[]]$To = @('ITStaff@mainstreetcu.ca'),
[string[]]$From = @('hvReplicaReporter@mainstreetcu.ca')
)
$mailParams = @{
SmtpServer = 'mainstreetcu-ca.mail.protection.outlook.com'
Port = 25
UseSSL = $true
From = $From
To = $To
Subject = $Subject
Body = $Message
BodyAsHtml = $true
DeliveryNotificationOption = 'OnFailure', 'OnSuccess'
}
Send-MailMessage @mailParams
}
#endregion Function Definitions
#region Main Script Execution
# Configure error handling behavior
$ErrorActionPreference = 'Stop'
#region Load Configuration
Write-Host 'Loading list of Hyper-V Host Servers from host list file...'
# Build path to host list file
$hostListPath = Join-Path -Path $PSScriptRoot -ChildPath 'hvhosts.json'
# Validate host list file exists
if (!(Test-Path -Path $hostListPath)) {
Write-Error ('hvhosts.json file not found at: {0}. See hvhostsExample.json.' -f $hostListPath)
exit
}
# Parse host list file
$jsonContent = Get-Content -Path $hostListPath -Raw
$hvHostConfig = ConvertFrom-Json -InputObject $jsonContent
$hvHosts = $hvHostConfig.hvHosts
# Display loaded configuration
Write-Host 'List of host servers loaded from host list file:'
$hvHosts | ForEach-Object { Write-Host ('- {0}' -f $_) }
#endregion Load Configuration
#region Collect Replication Data
Write-Host ('Retrieving virtual machine replication information from {0} Hyper-V hosts...' -f $hvHosts.Count)
# Initialize job tracking
$jobs = @()
$hostResults = @()
# Capture helper function definition so jobs can import it within their runspaces
$hostReplicationFuncDefinition = ${function:Get-HostReplicationAndSettings}.Ast.Extent.Text
# Capture time for $GenerationTimeStart
$GenerationTimeStart = Get-Date
# Start parallel jobs with throttling to avoid overwhelming system
foreach ($hvHost in $hvHosts) {
# Wait for a job slot to become available if at throttle limit
while ($jobs.Count -ge $ThrottleLimit) {
$finished = Wait-Job -Job $jobs -Any
$hostResults += Receive-Job -Job $finished
$jobs = $jobs | Where-Object { $_.Id -ne $finished.Id }
}
# Start background job to query this host
$jobs += Start-ThreadJob -ArgumentList $hvHost, $hostReplicationFuncDefinition -ScriptBlock {
param($hostName, $functionDefinition)
# Rehydrate Get-HostReplicationAndSettings inside this runspace
. ([scriptblock]::Create($functionDefinition))
Import-Module Hyper-V -ErrorAction Stop
Get-HostReplicationAndSettings -HostName $hostName
}
}
# Wait for remaining jobs to complete
if ($jobs.Count -gt 0) {
Wait-Job -Job $jobs | Out-Null
$hostResults += Receive-Job -Job $jobs
Remove-Job -Job $jobs -Force
}
# Extract replication info and VM settings from host results
$repInfo = $hostResults | ForEach-Object { $_.ReplicationInfo } | Where-Object { $_ }
$allVmSettings = $hostResults | ForEach-Object { $_.VmSettings } | Where-Object { $_ }
# Build fast lookup hashtable: "HostNameAlias|VMName" -> Settings object
# Include both short-name and FQDN aliases so replication relationships configured with
# either server-name format can still find the settings collected from hvhosts.json.
$settingsByHostAndName = @{}
foreach ($settingsRow in $allVmSettings) {
Add-VMSettingsLookupEntry -Lookup $settingsByHostAndName -SettingsRow $settingsRow
}
#endregion Collect Replication Data
#region Generate Report
Write-Host 'Generating report...'
# Generate HTML table from replication data
$repInfoHTML = $repInfo |
Sort-Object Name, Mode |
ConvertTo-Html -Fragment -Property Name, Mode, PrimaryServer, ReplicaServer, State, Health, FrequencySec, RelationshipType -PreContent '<div id="ReplicationTable">' -PostContent '</div>'
#endregion Generate Report
#region VM Settings Comparison
if (!$SkipSettingsCheck) {
Write-Host 'Performing VM settings check...'
# Identify VMs with replicas and categorize by replication mode
$namesOfVMsWithReplicas = ($repInfo |
Where-Object { $_.ReplicationMode -like '*Replica' } |
Select-Object -ExpandProperty Name -Unique |
Sort-Object)
$primaryVMs = $repInfo | Where-Object { $_.ReplicationMode -eq 'Primary' }
$replicaVMs = $repInfo | Where-Object { $_.ReplicationMode -eq 'Replica' }
$extendedReplicaVMs = $repInfo | Where-Object { $_.ReplicationMode -eq 'ExtendedReplica' }
# Initialize results array for replica settings comparison
$replicaSettingsMatch = @()
# Compare primary and replica VM settings
foreach ($vmName in $namesOfVMsWithReplicas) {
Write-Host ('Checking replica settings for VM: {0}' -f $vmName)
# Locate primary and replica VM objects
$primaryVM = $primaryVMs | Where-Object { $_.Name -eq $vmName }
$replicaVM = $replicaVMs | Where-Object { $_.Name -eq $vmName }
# Handle multiple replica VMs (can occur during Extended Replica initialization)
if ($replicaVM.Count -gt 1) {
Write-Host ('* Multiple replica VMs found for: {0}. Extended Replica initialization may be in progress.' -f $vmName)
$replicaVM = $replicaVM | Select-Object -First 1
Write-Host ('* Using first replica (Host: {0}) for comparison' -f $replicaVM.ReplicaServer)
}
# Retrieve cached settings using host aliases so short names and FQDNs both match
$primarySettings = Get-VMSettingsFromLookup -Lookup $settingsByHostAndName -HostName $primaryVM.PrimaryServer -VMName $vmName
$replicaSettings = Get-VMSettingsFromLookup -Lookup $settingsByHostAndName -HostName $replicaVM.ReplicaServer -VMName $vmName
# Perform comparison if both settings are available
if ($null -eq $primarySettings -or $null -eq $replicaSettings) {
Write-Warning ('Could not find cached settings for primary/replica pair: {0}' -f $vmName)
$settingsMatch = $null
}
else {
$settingsMatch = Test-VMSettingsEqual -PrimarySettings $primarySettings -ReplicaSettings $replicaSettings
}
# Store comparison result
$replicaSettingsMatch += New-Object -TypeName PSObject -Property @{
VMName = $vmName
SettingsMatch = $settingsMatch
}
}
# Initialize results array for extended replica settings comparison
$extendedReplicaSettingsMatch = @()
# Compare primary and extended replica VM settings
foreach ($vmName in $namesOfVMsWithReplicas) {
# Locate primary and extended replica VM objects
$primaryVM = $primaryVMs | Where-Object { $_.Name -eq $vmName }
$extendedReplicaVM = $extendedReplicaVMs | Where-Object { $_.Name -eq $vmName }
# Skip if this VM doesn't have an extended replica
if ($null -eq $extendedReplicaVM) {
continue
}
Write-Host ('Checking extended replica settings for VM: {0}' -f $vmName)
# Retrieve cached settings using host aliases so short names and FQDNs both match
$primarySettings = Get-VMSettingsFromLookup -Lookup $settingsByHostAndName -HostName $primaryVM.PrimaryServer -VMName $vmName
$extendedReplicaSettings = Get-VMSettingsFromLookup -Lookup $settingsByHostAndName -HostName $extendedReplicaVM.ReplicaServer -VMName $vmName
# Perform comparison if both settings are available
if ($null -eq $primarySettings -or $null -eq $extendedReplicaSettings) {
Write-Warning ('Could not find cached settings for primary/extended replica pair: {0}' -f $vmName)
$settingsMatch = $null
}
else {
$settingsMatch = Test-VMSettingsEqual -PrimarySettings $primarySettings -ReplicaSettings $extendedReplicaSettings
}
# Store comparison result
$extendedReplicaSettingsMatch += New-Object -TypeName PSObject -Property @{
VMName = $vmName
SettingsMatch = $settingsMatch
}
}
# Build consolidated report showing both replica and extended replica comparison results
$replicaReport = @()
foreach ($vmName in $namesOfVMsWithReplicas) {
$replicaReport += New-Object -TypeName PSObject -Property @{
Name = $vmName
ReplicaSettingsMatch = $replicaSettingsMatch |
Where-Object { $_.VMName -eq $vmName } |
Select-Object -ExpandProperty SettingsMatch
ExtendedReplicaSettingsMatch = $extendedReplicaSettingsMatch |
Where-Object { $_.VMName -eq $vmName } |
Select-Object -ExpandProperty SettingsMatch
}
}
# Generate HTML table from settings comparison report
$replicaReportHTML = $replicaReport |
Sort-Object Name |
ConvertTo-Html -Fragment -Property Name, ReplicaSettingsMatch, ExtendedReplicaSettingsMatch -PreContent '<div id="SettingsMatchTable">' -PostContent '</div>'
# Append settings comparison table to main replication report
$repInfoHTML = $repInfoHTML + '<br />' + $replicaReportHTML
}
#endregion VM Settings Comparison
# Capture time for $GenerationTimeEnd
$GenerationTimeEnd = Get-Date
#region Finalize HTML Report
Write-Host 'Appending time and date stamp to report...'
# Add timestamp to report for freshness tracking, including generation duration
$generationDuration = $GenerationTimeEnd - $GenerationTimeStart
$genMinutes = $generationDuration.Minutes
$genSeconds = $generationDuration.Seconds
$minutesLabel = if ($genMinutes -eq 1) { 'minute' } else { 'minutes' }
$secondsLabel = if ($genSeconds -eq 1) { 'second' } else { 'seconds' }
$repInfoHTML = $repInfoHTML + ('<div id="dateStamp">Report created on {0}, at {1}. (Generated in {2} {3} and {4} {5}.)</div>' -f
(Get-Date).ToString('MMM dd, yyyy'),
(Get-Date).ToString('h:mm:ss tt'),
$genMinutes,
$minutesLabel,
$genSeconds,
$secondsLabel
)
# Define CSS styling for the HTML report
$htmlHeader = @"
<style>
body
{
font-family: 'Hack', monospace;
}
table
{
border-width: 1px;
border-style: solid;
border-color: black;
border-collapse: collapse;
}
th
{
border-width: 1px;
padding: 3px;
border-style: solid;
border-color: black;
background-color: #6495ED;
}
td
{
border-width: 1px;
padding: 3px;
border-style: solid;
border-color: black;
}
tbody tr:nth-child(odd)
{
background-color: lightgray;
color: black;
}
div#dateStamp
{
font-size: 12px;
font-style: italic;
font-weight: normal;
margin-top: 6px;
}
</style>
"@
# Define JavaScript for interactive report features
$htmlFooter = @"
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
// Color-code boolean values in table cells (True = green, False = red)
const tds = document.getElementsByTagName('td');
const tdsLength = tds.length;
for (let i = 0; i < tdsLength; i++) {
const textContent = tds[i].textContent;
if (textContent === 'False') {
tds[i].style.color = 'red';
} else if (textContent === 'True') {
tds[i].style.color = 'green';
}
}
// Color-code Health column values (Normal = green, others = red)
const table = document.querySelector('#ReplicationTable table');
if (table) {
const headers = table.getElementsByTagName('th');
let healthColumnIndex = -1;
// Find the Health column index
Array.from(headers).forEach((header, index) => {
if (header.textContent.trim() === 'Health') {
healthColumnIndex = index;
}
});
// Apply color coding to Health column cells
if (healthColumnIndex !== -1) {
const rows = table.getElementsByTagName('tr');
const rowsLength = rows.length;
for (let i = 1; i < rowsLength; i++) { // Start at 1 to skip header row
const cells = rows[i].getElementsByTagName('td');
const healthCell = cells[healthColumnIndex];
if (healthCell) {
const healthText = healthCell.textContent.trim();
healthCell.style.color = healthText === 'Normal' ? 'green' : 'red';
}
}
}
}
// Highlight matching VM names across tables on hover
const tableRows = document.querySelectorAll('table tr');
tableRows.forEach(row => {
row.addEventListener('mouseover', () => {
const firstCell = row.cells[0];
const valueToMatch = firstCell.textContent;
tableRows.forEach(otherRow => {
if (otherRow === row) {
// Highlight the currently hovered row (bright yellow)
row.style.backgroundColor = '#FBF719';
} else if (otherRow.cells[0].textContent === valueToMatch) {
// Highlight matching VM names in other tables (dimmer yellow)
otherRow.style.backgroundColor = '#E1DE16';
}
});
});
row.addEventListener('mouseout', () => {
// Clear all row highlighting when mouse leaves
tableRows.forEach(otherRow => {
otherRow.style.backgroundColor = '';
});
});
});
// Check report age and display warning if stale
const dateStampText = document.getElementById('dateStamp').textContent;
const dateTimeString = dateStampText.match(/on (.+), at (.+)/);
const dateString = dateTimeString[1];
const timeString = dateTimeString[2];
const fullDateTimeString = ```${dateString} `${timeString}``;
// Parse report timestamp and calculate age
const reportDate = new Date(fullDateTimeString);
const currentDate = new Date();
const timeDifference = currentDate - reportDate;
const timeDifferenceInMinutes = timeDifference / (1000 * 60);
// Display warning if report exceeds configured age threshold
if (timeDifferenceInMinutes > $MaxReportAgeInMinutes) {
const dateStampDiv = document.getElementById('dateStamp');
// Move timestamp to top of page
document.body.insertBefore(dateStampDiv, document.body.firstChild);
// Style as prominent warning
dateStampDiv.style.fontSize = '2em';
dateStampDiv.style.fontWeight = 'bold';
dateStampDiv.style.color = 'red';
// Add warning message
const warningDiv = document.createElement('div');
warningDiv.style.color = 'black';
warningDiv.style.fontSize = '1.5em';
warningDiv.style.fontStyle = 'italic';
warningDiv.textContent = 'Report may be out of date, please confirm!';
dateStampDiv.insertAdjacentElement('afterend', warningDiv);
console.log('The report date is more than $MaxReportAgeInMinutes minutes ago.');
} else {
console.log('The report date is within the last $MaxReportAgeInMinutes minutes.');
}
});
</script>
"@
# Assemble complete HTML document
$htmlTemplate = @"
<html>
<head>
$htmlHeader
</head>
<body>
$repInfoHTML
</body>
$htmlFooter
</html>
"@
# Write the HTML report to disk
Write-Host ('Writing the HTML report file to: {0}' -f $ReportFilePath)
$htmlTemplate | Out-File $ReportFilePath
Write-Host 'Report generation completed.'
#endregion Finalize HTML Report
#endregion Main Script Execution