-
Notifications
You must be signed in to change notification settings - Fork 6.6k
Expand file tree
/
Copy pathGet-CIPPAlertMXRecordChanged.ps1
More file actions
70 lines (63 loc) · 3.14 KB
/
Get-CIPPAlertMXRecordChanged.ps1
File metadata and controls
70 lines (63 loc) · 3.14 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
function Get-CIPPAlertMXRecordChanged {
<#
.FUNCTIONALITY
Entrypoint
#>
[CmdletBinding()]
param (
[Parameter(Mandatory)]
$TenantFilter,
[Alias('input')]
$InputValue
)
try {
$DomainData = Get-CIPPDomainAnalyser -TenantFilter $TenantFilter
$CacheTable = Get-CippTable -tablename 'CacheMxRecords'
$PreviousResults = Get-CIPPAzDataTableEntity @CacheTable -Filter "PartitionKey eq '$TenantFilter'"
if (!$DomainData) {
return
}
$ChangedDomains = foreach ($Domain in $DomainData) {
try {
$PreviousDomain = $PreviousResults | Where-Object { $_.Domain -eq $Domain.Domain }
$PreviousRecords = if ($PreviousDomain.ActualMXRecords) { @($PreviousDomain.ActualMXRecords -split ',' | Sort-Object) } else { @() }
$CurrentRecords = if ($Domain.ActualMXRecords.Hostname) { @($Domain.ActualMXRecords.Hostname | Sort-Object) } else { @() }
# Only compare if both have records
$Differences = $null
if ($PreviousRecords.Count -gt 0 -and $CurrentRecords.Count -gt 0) {
$Differences = Compare-Object -ReferenceObject $PreviousRecords -DifferenceObject $CurrentRecords
}
if ($PreviousRecords.Count -eq 0 -and $CurrentRecords.Count -gt 0) {
Write-Information "New MX records detected for domain $($Domain.Domain): $($CurrentRecords -join ', ')"
$Differences = 'NewRecords'
} elseif ($PreviousRecords.Count -gt 0 -and $CurrentRecords.Count -eq 0) {
Write-Information "All MX records removed for domain $($Domain.Domain). Previous records were: $($PreviousRecords -join ', ')"
$Differences = 'RemovedRecords'
}
if ($Differences) {
"$($Domain.Domain): MX records changed from [$($PreviousRecords -join ', ')] to [$($CurrentRecords -join ', ')]"
}
} catch {
Write-Information "Error checking domain $($Domain.Domain): $($_.Exception.Message)"
}
}
# Update cache with current data
foreach ($Domain in $DomainData) {
$CurrentRecords = @($Domain.ActualMXRecords.Hostname | Sort-Object)
$CacheEntity = @{
PartitionKey = [string]$TenantFilter
RowKey = [string]$Domain.Domain
Domain = [string]$Domain.Domain
ActualMXRecords = [string]($CurrentRecords -join ',')
LastRefresh = [string]$Domain.LastRefresh
MailProvider = [string]$Domain.MailProvider
}
Add-CIPPAzDataTableEntity @CacheTable -Entity $CacheEntity -Force
}
if ($ChangedDomains) {
Write-AlertTrace -cmdletName $MyInvocation.MyCommand -tenantFilter $TenantFilter -data $ChangedDomains
}
} catch {
Write-LogMessage -message "Failed to check MX record changes: $($_.Exception.Message)" -API 'MX Record Alert' -tenant $TenantFilter -sev Error
}
}