Friday, November 20, 2026

Hybrid Exchange: Why On-Prem App Emails Miss Cloud Mailboxes, and How RemoteMailbox Fixes It

Scope: hybrid Exchange (on-premises Exchange 2016/2019 + Exchange Online + Microsoft Entra Connect), where on-premises applications send mail through an on-prem relay.

Why this matters

  • Many on-premises apps (issue trackers, wikis, build servers, monitoring tools) send notifications to an on-premises SMTP relay, not straight to Exchange Online.
  • The relay decides where to deliver by looking up the recipient in on-prem Active Directory / Exchange.
  • If the user's on-prem object is not a mail-enabled recipient, the relay has no route, even though the user has a working cloud mailbox.
  • Result: the user gets normal mail from the internet and other cloud users, but nothing from internal on-prem apps.

How hybrid routing works for a cloud mailbox

  • Every cloud mailbox user in a hybrid org should exist on-prem as a RemoteUserMailbox.
  • That object carries a targetAddress (the remote routing address, usually user@tenant.mail.onmicrosoft.com).
  • On-prem transport sees the RemoteUserMailbox, rewrites delivery to the targetAddress, and sends it over the hybrid connector to Exchange Online.
  • If the object is a plain AD user, transport tries to find a local mailbox database, finds none, and defers the message.
On-prem object stateWhat on-prem transport doesOutcome
RemoteUserMailbox with targetAddressRoutes to the onmicrosoft addressDelivered to the cloud mailbox
Plain user, no Exchange attributesLooks for a local mailbox databaseDeferred: 420 4.2.0 Recipient deferred because there is no Mdb
MailUser pointing at a wrong or stale addressRoutes to that addressLost, bounced or looped

When the gap appears

  • Account type conversions (contractor to employee, re-hire, rejoin) where a new AD account is created and the mailbox is provisioned in the cloud directly.
  • Mailboxes created in Exchange Online first, then matched to an on-prem account later.
  • Manual clean-up of Exchange attributes during offboarding, then re-use of the account.
  • Provisioning scripts that set mail and proxyAddresses but never call an Exchange cmdlet.

Key attributes to know

AD attributeHealthy value for a cloud mailbox userMeaning
msExchRecipientTypeDetails2147483648RemoteUserMailbox
msExchRemoteRecipientType1 (ProvisionMailbox) or 4 (Migrated)How the cloud mailbox came to exist
targetAddressSMTP:user@tenant.mail.onmicrosoft.comWhere on-prem transport forwards mail
msExchMailboxGuid (ExchangeGuid)Same GUID as the Exchange Online mailboxLinks the on-prem object to the existing cloud mailbox
proxyAddressesSMTP:primary plus aliasesMust match the cloud primary address

Recognising the pattern

  • Exchange Online message trace shows zero messages from the on-prem app sender to the user, while the same sender delivers to everyone else.
  • The user's cloud mailbox receives other mail normally; no inbox rules or blocked senders.
  • Get-ADUser shows empty msExchRecipientTypeDetails and targetAddress.
  • On-prem tracking logs or queues show DEFER with "no Mdb" for that recipient.
  • Important: Exchange Online trace cannot see this, because the mail never leaves on-prem.

The fix

  • Step 1: read the cloud mailbox ExchangeGuid from Exchange Online.
  • Step 2: on on-prem Exchange, run Enable-RemoteMailbox with the onmicrosoft routing address.
  • Step 3: run Set-RemoteMailbox -ExchangeGuid so the on-prem object points at the existing cloud mailbox.
  • Step 4: confirm the primary SMTP address did not change (email address policies can add or reorder addresses).
  • Step 5: let Entra Connect sync (or run a delta sync), retry deferred queues, and send a test notification.

Things to watch

  • Enable-RemoteMailbox and Set-RemoteMailbox exist only in on-premises Exchange. They are not in the Exchange Online module.
  • Running both modules in one window causes cmdlet name clashes. Use Connect-ExchangeOnline -Prefix Cloud or separate windows.
  • Skipping the ExchangeGuid step can lead to sync trying to provision a second mailbox or a mailbox conflict.
  • An email address policy may stamp extra aliases from on-prem-only domains. Unverified domains are dropped by the cloud during sync, which is harmless.
  • In an imported remote session, piping Get-TransportService into Get-MessageTrackingLog or Get-Queue does not bind. Loop with -Server instead.
  • Get-MessageTraceV2 -Subject requires -SubjectFilterType (Contains, StartsWith or EndsWith).
  • Routing works as soon as AD replication and the transport recipient cache catch up; the sync mainly keeps the cloud object consistent.
  • Always export the current attributes before changing them.

My thoughts

  • This is a process gap, not a product bug. The joiner/converter workflow creates the identity and the cloud mailbox but skips the on-prem Exchange step.
  • The fix belongs in the account conversion runbook: any new or converted account that gets a cloud mailbox should be created with New-RemoteMailbox or Enable-RemoteMailbox, never by setting attributes by hand.
  • A scheduled check (section 9 of the script) that lists users with a primary SMTP but no recipient type catches these before users notice.
  • When an on-prem app "stops emailing one person", check on-prem routing first. A clean Exchange Online trace often means the problem is upstream, not that mail flow is healthy.
  • As long as on-prem apps relay through Exchange, the on-prem recipient objects matter, even when every mailbox is in the cloud.

References

Full script

  • Plain variables at the top, no parameter block, so it can be run line by line.
  • Sample names (contoso) only. Replace them with your own values.
# =====================================================================
# Hybrid RemoteMailbox check and fix for a user whose mailbox is in
# Exchange Online but whose on-premises AD account is not mail-enabled.
# Run line by line or section by section. Replace the sample values first.
# Requires: ActiveDirectory module, ExchangeOnlineManagement module,
#           network access to an on-premises Exchange 2016/2019 server.
# =====================================================================

# ---------- Variables (edit these) ----------
$samAccount   = 'jdoe1'                               # On-prem sAMAccountName of the user
$primarySmtp  = 'John.Doe1@contoso.com'               # Primary SMTP address used in Exchange Online
$routingAddr  = 'John.Doe1@contoso.mail.onmicrosoft.com'  # Tenant routing (onmicrosoft) address
$adminUpn     = 'admin@contoso.com'                   # Account used to connect to Exchange Online
$exchServer   = 'exch01.contoso.local'                # On-prem Exchange server FQDN
$appSender    = 'noreply-app@contoso.com'             # Sender address of the on-prem application
$backupPath   = "$env:USERPROFILE\$samAccount" + '_before.csv'

# ---------- 1. Inspect the on-prem AD object ----------
# Empty msExchRecipientTypeDetails and targetAddress means the account
# is not mail-enabled, so on-prem Exchange cannot route mail for it.
$adUser = Get-ADUser -Identity $samAccount -Properties mail, proxyAddresses, targetAddress, msExchRecipientTypeDetails, msExchRemoteRecipientType
$adUser | Format-List SamAccountName, UserPrincipalName, mail, targetAddress, msExchRecipientTypeDetails, msExchRemoteRecipientType, proxyAddresses

if ($adUser.msExchRecipientTypeDetails -eq 2147483648) {
    Write-Host 'User is already a RemoteUserMailbox. No fix needed.' -ForegroundColor Green
} else {
    Write-Host 'User is NOT a RemoteUserMailbox. Continue with the fix.' -ForegroundColor Yellow
}

# ---------- 2. Back up current attributes (rollback reference) ----------
$adUser | Select-Object SamAccountName, mail, targetAddress,
    @{n='proxyAddresses';e={$_.proxyAddresses -join ';'}} |
    Export-Csv -Path $backupPath -NoTypeInformation
Write-Host "Backup saved to $backupPath"

# ---------- 3. Get the ExchangeGuid of the cloud mailbox ----------
# -Prefix Cloud keeps Exchange Online cmdlets separate from on-prem ones
# (Get-CloudMailbox instead of Get-Mailbox) in the same window.
Connect-ExchangeOnline -UserPrincipalName $adminUpn -Prefix Cloud -ShowBanner:$false
$cloudMbx     = Get-CloudMailbox -Identity $primarySmtp
$exchangeGuid = $cloudMbx.ExchangeGuid
$cloudMbx | Format-List DisplayName, PrimarySmtpAddress, ExchangeGuid

# ---------- 4. Connect to on-prem Exchange ----------
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://$exchServer/PowerShell/" -Authentication Kerberos
Import-PSSession $session -DisableNameChecking -AllowClobber | Out-Null

# ---------- 5. Mail-enable as RemoteMailbox and stamp the ExchangeGuid ----------
# Enable-RemoteMailbox sets targetAddress so the relay can route to the cloud.
# Matching ExchangeGuid ties the on-prem object to the existing cloud mailbox
# instead of letting sync treat it as a new mailbox to provision.
Enable-RemoteMailbox -Identity $samAccount -RemoteRoutingAddress $routingAddr
Set-RemoteMailbox    -Identity $samAccount -ExchangeGuid $exchangeGuid

# ---------- 6. Verify ----------
$remote = Get-RemoteMailbox -Identity $samAccount
$remote | Format-List Name, PrimarySmtpAddress, RemoteRoutingAddress, ExchangeGuid, EmailAddressPolicyEnabled, EmailAddresses

# An email address policy can change the primary address. Put it back if needed.
if ($remote.PrimarySmtpAddress.ToString() -ne $primarySmtp) {
    Write-Host 'Primary SMTP changed by policy. Restoring it.' -ForegroundColor Yellow
    Set-RemoteMailbox -Identity $samAccount -PrimarySmtpAddress $primarySmtp -EmailAddressPolicyEnabled $false
} else {
    Write-Host 'Primary SMTP address unchanged.' -ForegroundColor Green
}

if ($remote.ExchangeGuid -ne $exchangeGuid) {
    Write-Warning 'ExchangeGuid does not match the cloud mailbox. Do not sync until fixed.'
} else {
    Write-Host 'ExchangeGuid matches the cloud mailbox.' -ForegroundColor Green
}

# ---------- 7. Retry anything deferred for missing routing ----------
# Run per server: piping Get-TransportService into queue cmdlets
# does not bind in an imported remote session.
$transportServers = (Get-TransportService).Name
foreach ($srv in $transportServers) {
    Get-Queue -Server $srv | Where-Object { $_.LastError -match 'no Mdb' } | Retry-Queue
}

# ---------- 8. Test end to end after a new application notification ----------
# On-prem: expect RECEIVE then SEND (not DEFER).
$onPremLog = foreach ($srv in $transportServers) {
    Get-MessageTrackingLog -Server $srv -Recipients $primarySmtp -Start (Get-Date).AddHours(-2) -ResultSize Unlimited
}
$onPremLog | Sort-Object Timestamp | Format-Table Timestamp, ServerHostname, EventId, Sender, MessageSubject -AutoSize

# Exchange Online: expect Delivered.
Get-CloudMessageTraceV2 -SenderAddress $appSender -RecipientAddress $primarySmtp -StartDate (Get-Date).AddHours(-2) -EndDate (Get-Date) |
    Format-Table Received, RecipientAddress, Status, Subject -AutoSize

# ---------- 9. Optional: find other users with the same gap ----------
# Users that have a primary SMTP in proxyAddresses but no Exchange recipient type.
Get-ADUser -Filter 'Enabled -eq $true' -Properties proxyAddresses, msExchRecipientTypeDetails |
    Where-Object { ($_.proxyAddresses -cmatch '^SMTP:') -and (-not $_.msExchRecipientTypeDetails) } |
    Select-Object SamAccountName, UserPrincipalName,
        @{n='PrimarySmtp';e={($_.proxyAddresses -cmatch '^SMTP:') -replace '^SMTP:'}} |
    Format-Table -AutoSize

# ---------- 10. Clean up ----------
Remove-PSSession $session
Disconnect-ExchangeOnline -Confirm:$false

Thursday, November 19, 2026

Microsoft 365 Custom Domains & DNS Records (MX, TXT, CNAME, SRV)

Microsoft 365 Custom Domains & DNS Records (MX, TXT, CNAME, SRV)

Category: Microsoft 365 Administration › Domains › DNS Audience: M365 administrators, messaging/identity engineers, service desk (L2/L3) Applies to: Microsoft 365, Exchange Online, Microsoft Entra ID, Intune, Teams, Azure DNS (or any DNS host)


1. Purpose

  • Explain every DNS record Microsoft 365 uses for a custom domain and what each one does.
  • Show where to find expected values, the exact clicks, and what to enter at the DNS host.
  • Show how to confirm what is live in public DNS for each record type.
  • Give an answer pack for partner requests (eFax, banks, vendors) asking for MX / MTA / TLS details.
  • Provide a PowerShell script that reports expected vs live for all record types across every domain in the tenant.

2. Key Terms

TermFull formMeaning
DNS zone–All records for one domain, hosted at a DNS provider (Azure DNS, Cloudflare, GoDaddy…)
MXMail ExchangerWhich server receives email for the domain
TXTTextFree-text record – used for SPF, DMARC and domain verification
CNAMECanonical NameAlias from one name to another (Autodiscover, DKIM, Intune)
SRVService locatorPoints a service + protocol + port to a host (legacy Skype/Teams federation)
A / AAAAAddressHostname → IPv4 / IPv6
SPFSender Policy FrameworkTXT listing servers allowed to send as the domain
DKIMDomainKeys Identified MailCryptographic signature on outgoing mail (published as CNAMEs)
DMARCDomain-based Message Authentication, Reporting & ConformancePolicy telling receivers what to do when SPF/DKIM fail
MTAMail Transfer AgentMail server that accepts/relays email (M365 = Exchange Online Protection)
EOPExchange Online ProtectionMicrosoft's inbound mail gateway
TTLTime To LiveCache time in seconds (3600 = 1 hour)
Priority / Preference–Lower number = higher priority (0 is highest)
@–Shorthand for the root (apex) of the domain, e.g. contoso.com

3. Record Map – What Each Record Is For

ServiceRecordHost / NameWithout it…
Domain ownershipTXT@ → MS=msXXXXXXXXDomain can't be verified/added to the tenant
Inbound emailMX@Mail never reaches Exchange Online
Outbound email trustTXT (SPF)@Mail marked as spam / spoofable
Outbound email signingCNAME (DKIM) ×2selector1._domainkey, selector2._domainkeyNo DKIM – weaker deliverability, DMARC relies on SPF only
Email policyTXT (DMARC)_dmarcNo spoofing enforcement or reporting
Outlook setupCNAMEautodiscoverUsers must configure Outlook manually
Device registrationCNAMEenterpriseregistrationUsers must type server address for Entra device registration
Intune enrollmentCNAMEenterpriseenrollmentUsers must type server address during MDM enrollment
Legacy Skype / Teams federationCNAME ×2, SRV ×2sip, lyncdiscover, _sip._tls, _sipfederationtls._tcpOnly needed if the admin center lists them for your setup

4. Standard Record Values

4.1 Email (Exchange Online)

TypeName / HostValue / TargetPriorityTTL
MX@<domain-key>.mail.protection.outlook.com (e.g. contoso-com.mail.protection.outlook.com)03600
TXT (SPF)@v=spf1 include:spf.protection.outlook.com -all–3600
CNAMEautodiscoverautodiscover.outlook.com–3600
CNAME (DKIM)selector1._domainkeyCopy from Defender portal / admin center–3600
CNAME (DKIM)selector2._domainkeyCopy from Defender portal / admin center–3600
TXT (DMARC)_dmarcv=DMARC1; p=none; rua=mailto:dmarc-reports@contoso.com (start) → p=quarantine → p=reject–3600

Rules to remember

  • MX: copy from the admin center; Exchange Online supports MX TTL under 6 hours only. Newer DNSSEC/DANE domains may show a *.mx.microsoft host – still EOP.
  • SPF: only one SPF TXT per domain. If another service also sends mail, merge the includes into the single record (e.g. v=spf1 include:spf.protection.outlook.com include:_spf.partner.example -all).
  • SPF lookups: maximum 10 DNS lookups per SPF evaluation – too many include: entries break SPF.
  • DKIM: CNAMEs only work after you enable DKIM signing for the domain (section 7).
  • DMARC: roll out gradually – p=none (monitor) → p=quarantine → p=reject.

4.2 Identity & Device Management

TypeName / HostValue / TargetTTL
TXT (verification)@MS=msXXXXXXXX (unique per tenant – copy from admin center)3600
CNAMEenterpriseregistrationenterpriseregistration.windows.net3600
CNAMEenterpriseenrollmententerpriseenrollment-s.manage.microsoft.com3600
  • Keep the verification TXT after verification – it does no harm and helps if the domain is ever re-validated.

4.3 Legacy Skype for Business / Teams Federation (only if listed in the admin center)

TypeName / HostValue / TargetPortPriorityWeight
CNAMEsipsipdir.online.lync.com–––
CNAMElyncdiscoverwebdir.online.lync.com–––
SRV_sip._tlssipdir.online.lync.com4431001
SRV_sipfederationtls._tcpsipfed.online.lync.com50611001

5. Where to Find Expected Records (Microsoft 365 Admin Center)

Role needed to view: Global Reader, Domain Name Administrator or Global Administrator.

StepWhere to go / what to clickWhat you'll see
1Open https://admin.cloud.microsoft and sign inAdmin center home
2Left menu → … Show all → Settings → Domains (direct: https://admin.cloud.microsoft/#/Domains)Every domain with Status (Healthy / Incomplete setup / Possible service issues)
3Click the domain name (e.g. contoso.com)Tabs: Overview, DNS records, Users, Teams & groups, Apps
4Click DNS recordsRecords grouped by service: Microsoft Exchange, Basic Mobility and Security / Intune, Skype for Business
5Click a record's radio buttonSide panel with Type, Name, Value/Points to, Priority, TTL – use the copy icons
6Optional: Download CSV file, Download zone file, Print (above the list)Export for change records / DNS team hand-off
7Optional: Manage DNS → More options → Add your own DNS → ContinueWizard listing records to add, incl. Advanced options (DKIM, Intune)

Reading the page

  • Banner "To manage DNS records for … go to your DNS hosting provider: Azure" → tells you where to edit.
  • Banner "Some of your DNS records aren't set up correctly" → at least one live record differs; check section 6.
  • "Federated domain" in the header = sign-in federated to an external IdP. It does not affect MX/TXT/CNAME values.
  • Ignore system domains (*.onmicrosoft.com, *.mail.onmicrosoft.com, *.pstn.for-teams.com).

6. Confirm Live Records (Public DNS)

6.1 Commands per record type (PowerShell)

RecordCommandField to read
MXResolve-DnsName contoso.com -Type MX -Server 8.8.8.8NameExchange, Preference
SPF / verification TXTResolve-DnsName contoso.com -Type TXT -Server 8.8.8.8Strings (look for v=spf1 and MS=ms)
DMARCResolve-DnsName _dmarc.contoso.com -Type TXT -Server 8.8.8.8Strings (starts v=DMARC1)
AutodiscoverResolve-DnsName autodiscover.contoso.com -Type CNAME -Server 8.8.8.8NameHost
DKIMResolve-DnsName selector1._domainkey.contoso.com -Type CNAME -Server 8.8.8.8NameHost
IntuneResolve-DnsName enterpriseenrollment.contoso.com -Type CNAME -Server 8.8.8.8NameHost
SRVResolve-DnsName _sipfederationtls._tcp.contoso.com -Type SRV -Server 8.8.8.8NameTarget, Port, Priority, Weight
  • -Server 8.8.8.8 queries a public resolver – avoids internal split-brain DNS answers.
  • nslookup -type=<TYPE> <name> works the same in Command Prompt.

6.2 Azure DNS (if the zone is in Azure)

StepWhere / clickWhat you'll see
1https://portal.azure.com → search DNS zonesList of zones
2Click the zone (e.g. contoso.com)Overview with name servers
3Left menu → DNS Management → RecordsetsAll records – filter by Type (MX, TXT, CNAME, SRV)
4Click a record setName, Type, TTL, Value(s) – edit only via approved change

6.3 Web tools

ToolWhere / buttonUse for
MXToolboxhttps://mxtoolbox.com → MX Lookup / SPF Record Lookup / DMARC Lookup / DKIM LookupQuick external validation and syntax checks
MXToolbox SMTP Testhttps://mxtoolbox.com → SMTP TestTLS / STARTTLS on the MX host

7. Enable DKIM (Microsoft Defender Portal)

StepWhere / clickWhat to enter
1https://security.microsoft.com → Email & collaboration → Policies & rules → Threat policies–
2Email authentication settings → DKIM tabList of domains with DKIM status
3Click the domainFlyout shows the two CNAME values
4Publish both CNAMEs at the DNS host (section 4.1)Host selector1._domainkey / selector2._domainkey
5Wait for DNS propagation, then toggle Sign messages for this domain with DKIM signatures to Enabled–

Direct link: https://security.microsoft.com/authentication?viewid=DKIM


8. Answer Pack – Partner TLS Email Requests (eFax, Banks, Vendors)

Form fieldSelect / enterWhy
Domain Namecontoso.com (one row per domain)Each accepted domain is separate
Delivery Point☑ MX RecordPreferred – Microsoft IPs rotate
A Record / IP AddressLeave blankNot used with MX
Specific MTAcontoso-com.mail.protection.outlook.comEOP hostname from the MX
Certificate Authority☑ Third-PartyEOP uses a public-CA certificate (subject mail.protection.outlook.com)

Reply template

TLS details for our email domains:

• contoso.com  – Delivery: MX Record – MTA: contoso-com.mail.protection.outlook.com  – CA: Third-Party
• fabrikam.com – Delivery: MX Record – MTA: fabrikam-com.mail.protection.outlook.com – CA: Third-Party

Hosted on Microsoft Exchange Online (public-CA certificates).
Please do not use IP addresses – Microsoft rotates them.

Checklist before sending

  • Live MX matches the admin center for each domain
  • No third-party gateway in front – if there is, give that hostname and that vendor's CA
  • Only customer-facing domains listed
  • Request logged in your ticketing system

Optional – force TLS: https://admin.exchange.microsoft.com → Mail flow → Connectors → + Add a connector → Partner organization → Office 365 → ☑ Reject email messages if they aren't sent over TLS. Validate before enabling – a wrong connector rejects mail.


9. Best Practices & Ideas

#RecommendationBenefit
1Run the script below monthly (Azure Automation / scheduled task) and alert on any Mismatch / MissingCatches accidental DNS edits before users notice
2One SPF per domain, under 10 lookups, ending in -allReliable SPF pass
3Enable DKIM for every sending domainStronger authentication, DMARC alignment
4Roll DMARC from p=none → quarantine → reject while reviewing rua reportsBlocks spoofing without breaking legitimate mail
5Park unused domains: v=spf1 -all, DMARC p=reject, null MX (0 .)Stops attackers abusing idle domains
6Hand partners hostnames, never IPsNo breakage when Microsoft rotates IPs
7Drop TTL to 300 a day before a planned change, restore to 3600 afterFast cut-over and rollback
8Remove legacy Skype SRV/CNAMEs only after confirming the admin center no longer lists themClean zone without breaking federation
9Keep a domain fact sheet (domain, DNS host, MX, DKIM status, DMARC policy, owner)Answer audits / partner forms in minutes
10Use Global Reader for reporting; restrict DNS write accessLeast privilege
11Record every DNS change in change management with before/after exports (zone file)Audit trail and quick rollback
12Consider SMTP DANE with DNSSEC for Exchange Online inbound where supportedProtects TLS against downgrade attacks

10. Quick Reference

NeedGo to
Expected recordshttps://admin.cloud.microsoft/#/Domains → domain → DNS records
Edit Azure-hosted zonehttps://portal.azure.com → DNS zones → zone → Recordsets
DKIMhttps://security.microsoft.com/authentication?viewid=DKIM
TLS connectorshttps://admin.exchange.microsoft.com → Mail flow → Connectors
Live checkResolve-DnsName <name> -Type <MX/TXT/CNAME/SRV> -Server 8.8.8.8

11. References (Microsoft Learn)


12. Script – Tenant DNS Health Report (MX, TXT, CNAME, SRV + DKIM & DMARC)

What it does

  • Connects to Microsoft Graph with read-only scope Domain.Read.All.
  • Lists verified custom domains (skips onmicrosoft.com and Teams PSTN domains).
  • Reads every expected record Microsoft 365 requires (MX, TXT, CNAME, SRV) per domain.
  • Resolves the live value from public DNS for each record.
  • Adds extra checks Graph doesn't list: DMARC, DKIM selectors, multiple SPF records, SPF lookup count.
  • Flags each row Match / Mismatch / Missing / Info.
  • Exports a CSV and prints a summary of issues.

Prerequisites

  • Windows PowerShell 5.1 or PowerShell 7 on Windows (Resolve-DnsName).
  • Install-Module Microsoft.Graph.Identity.DirectoryManagement -Scope CurrentUser
  • Global Reader (or higher).
# =====================================================================
# Script : Get-M365DomainDnsHealthReport.ps1
# Purpose: Compare expected (Microsoft 365) vs live (public DNS) records
#          for every verified custom domain - MX, TXT, CNAME, SRV - plus
#          extra DKIM, DMARC and SPF hygiene checks.
# Notes  : No param() block - edit the variables below and run the
#          script top-to-bottom or line by line.
# =====================================================================

# ----------------------------- Variables -----------------------------
$PublicDnsServer   = "8.8.8.8"                                    # Public resolver (avoids internal/split DNS)
$ExportFolder      = "$env:USERPROFILE\Documents\DomainDnsReport" # CSV output folder
$IncludeOptional   = $true                                        # $true = also check records Microsoft marks optional
$CheckDkim         = $true                                        # $true = check selector1/selector2 DKIM CNAMEs
$CheckDmarc        = $true                                        # $true = check _dmarc TXT
$SpfLookupLimit    = 10                                           # RFC limit for DNS lookups in SPF
$ExcludePatterns   = @(                                           # System domains to skip
    "*.onmicrosoft.com",
    "*.pstn.for-teams.com"
)

# --------------------------- Prerequisites ---------------------------
# Load the Graph module that contains the domain cmdlets
Import-Module Microsoft.Graph.Identity.DirectoryManagement -ErrorAction Stop

# Sign in with a read-only scope (interactive prompt)
Connect-MgGraph -Scopes "Domain.Read.All" -NoWelcome

# Create the export folder if needed
if (-not (Test-Path $ExportFolder)) {
    New-Item -Path $ExportFolder -ItemType Directory | Out-Null
}

# Collection that every check adds rows to
$report = New-Object System.Collections.Generic.List[object]

# --------------------------- Helper blocks ---------------------------
# Resolve a DNS name safely and return only records of the requested type
# Usage: & $resolveLive <name> <type>   ($args[0] = name, $args[1] = type)
$resolveLive = {
    $lookupName = $args[0]
    $lookupType = $args[1]
    try {
        Resolve-DnsName -Name $lookupName -Type $lookupType -Server $PublicDnsServer -DnsOnly -ErrorAction Stop |
            Where-Object { $_.Type -eq $lookupType }
    } catch {
        @()
    }
}

# Add one result row to the report
# Usage: & $addRow <domain> <service> <type> <name> <expected> <live> <status> <optional>
$addRow = {
    $report.Add([PSCustomObject]@{
        Domain   = $args[0]
        Service  = $args[1]
        Type     = $args[2]
        Name     = $args[3]
        Expected = $args[4]
        Live     = $args[5]
        Status   = $args[6]
        Optional = $args[7]
    })
}

# ------------------------- Get tenant domains ------------------------
$domains = Get-MgDomain -All | Where-Object {
    $name = $_.Id
    $isExcluded = $false
    foreach ($pattern in $ExcludePatterns) {
        if ($name -like $pattern) { $isExcluded = $true }
    }
    (-not $isExcluded) -and $_.IsVerified
}

Write-Host "Domains to check: $($domains.Count)" -ForegroundColor Cyan

# ---------------------------- Main loop ------------------------------
foreach ($domain in $domains) {

    $domainName = $domain.Id
    Write-Host "Checking $domainName ..." -ForegroundColor Yellow

    # ---- Expected records from Microsoft 365
    try {
        $expectedRecords = Get-MgDomainServiceConfigurationRecord -DomainId $domainName -All -ErrorAction Stop
    } catch {
        Write-Warning "Cannot read expected records for $domainName : $($_.Exception.Message)"
        continue
    }

    foreach ($rec in $expectedRecords) {

        # Skip optional records if requested
        if ($rec.IsOptional -and -not $IncludeOptional) { continue }

        $props   = $rec.AdditionalProperties   # type-specific values live here
        $service = $rec.SupportedService       # Email, Intune, OfficeCommunicationsOnline, ...

        switch ($rec.RecordType) {

            # ---------------- MX ----------------
            "Mx" {
                $expected = "$($props['preference']) $($props['mailExchange'])"
                $live     = & $resolveLive $rec.Label "MX" | Sort-Object Preference
                $liveText = ($live | ForEach-Object { "$($_.Preference) $($_.NameExchange)" }) -join "; "

                if (-not $live) {
                    $status = "Missing"
                } elseif ($live.NameExchange -contains $props['mailExchange']) {
                    $status = "Match"
                    if ($live.Count -gt 1) { $status = "Match (multiple MX records)" }
                } else {
                    $status = "Mismatch"
                }
                & $addRow $domainName $service "MX" $rec.Label $expected $liveText $status $rec.IsOptional
            }

            # ---------------- TXT ---------------
            "Txt" {
                $expected = $props['text']
                $live     = & $resolveLive $rec.Label "TXT"
                $liveTxt  = $live | ForEach-Object { $_.Strings -join "" }

                if ($expected -like "v=spf1*") {
                    # SPF: pass if the single SPF record includes Microsoft
                    $liveSpf = $liveTxt | Where-Object { $_ -like "v=spf1*" }
                    if (-not $liveSpf) {
                        $status = "Missing"
                    } elseif (@($liveSpf).Count -gt 1) {
                        $status = "Mismatch (multiple SPF records)"
                    } elseif ($liveSpf -match "include:spf\.protection\.outlook\.com") {
                        $status = "Match"
                    } else {
                        $status = "Mismatch (Microsoft include missing)"
                    }
                    & $addRow $domainName $service "TXT (SPF)" $rec.Label $expected ($liveSpf -join "; ") $status $rec.IsOptional
                } else {
                    # Other TXT (e.g. verification): exact match on any string
                    if ($liveTxt -contains $expected) {
                        $status = "Match"
                    } else {
                        $status = "Missing"
                    }
                    & $addRow $domainName $service "TXT" $rec.Label $expected ($liveTxt -join "; ") $status $rec.IsOptional
                }
            }

            # --------------- CNAME --------------
            "CName" {
                $expected = $props['canonicalName']
                $live     = & $resolveLive $rec.Label "CNAME"
                $liveHost = ($live | Select-Object -First 1).NameHost

                if (-not $liveHost) {
                    $status = "Missing"
                } elseif ($liveHost.TrimEnd('.') -eq $expected.TrimEnd('.')) {
                    $status = "Match"
                } else {
                    $status = "Mismatch"
                }
                & $addRow $domainName $service "CNAME" $rec.Label $expected $liveHost $status $rec.IsOptional
            }

            # ---------------- SRV ---------------
            "Srv" {
                # DNS name = _service._protocol.label
                $srvName  = "$($props['service']).$($props['protocol']).$($rec.Label)"
                $expected = "$($props['priority']) $($props['weight']) $($props['port']) $($props['nameTarget'])"
                $live     = & $resolveLive $srvName "SRV" | Select-Object -First 1

                if (-not $live) {
                    $status   = "Missing"
                    $liveText = ""
                } else {
                    $liveText = "$($live.Priority) $($live.Weight) $($live.Port) $($live.NameTarget)"
                    if (($live.NameTarget.TrimEnd('.') -eq $props['nameTarget'].TrimEnd('.')) -and ($live.Port -eq $props['port'])) {
                        $status = "Match"
                    } else {
                        $status = "Mismatch"
                    }
                }
                & $addRow $domainName $service "SRV" $srvName $expected $liveText $status $rec.IsOptional
            }

            # -------------- Anything else -------
            default {
                & $addRow $domainName $service $rec.RecordType $rec.Label "" "" "Info (not checked)" $rec.IsOptional
            }
        }
    }

    # ---- Extra check: SPF DNS lookup count (include, a, mx, ptr, exists, redirect)
    $spfLive = (& $resolveLive $domainName "TXT" | ForEach-Object { $_.Strings -join "" }) | Where-Object { $_ -like "v=spf1*" } | Select-Object -First 1
    if ($spfLive) {
        $lookupCount = ([regex]::Matches($spfLive, '(?i)\b(include:|a\b|a:|mx\b|mx:|ptr|exists:|redirect=)')).Count
        if ($lookupCount -gt $SpfLookupLimit) {
            $status = "Mismatch (top-level lookups $lookupCount > $SpfLookupLimit)"
        } else {
            $status = "Info (top-level lookups: $lookupCount)"
        }
        & $addRow $domainName "Email" "TXT (SPF lookups)" $domainName "<= $SpfLookupLimit lookups" $spfLive $status $true
    }

    # ---- Extra check: DKIM selectors
    if ($CheckDkim) {
        foreach ($selector in @("selector1", "selector2")) {
            $dkimName = "$selector._domainkey.$domainName"
            $dkimLive = (& $resolveLive $dkimName "CNAME" | Select-Object -First 1).NameHost
            if ($dkimLive) {
                $status = "Match (CNAME present)"
            } else {
                $status = "Missing"
            }
            & $addRow $domainName "Email" "CNAME (DKIM)" $dkimName "Value from Defender portal" $dkimLive $status $true
        }
    }

    # ---- Extra check: DMARC
    if ($CheckDmarc) {
        $dmarcName = "_dmarc.$domainName"
        $dmarcLive = (& $resolveLive $dmarcName "TXT" | ForEach-Object { $_.Strings -join "" }) | Where-Object { $_ -like "v=DMARC1*" } | Select-Object -First 1

        if (-not $dmarcLive) {
            $status = "Missing"
        } elseif ($dmarcLive -match "p=reject") {
            $status = "Match (p=reject)"
        } elseif ($dmarcLive -match "p=quarantine") {
            $status = "Match (p=quarantine)"
        } else {
            $status = "Info (p=none - monitoring only)"
        }
        & $addRow $domainName "Email" "TXT (DMARC)" $dmarcName "v=DMARC1; p=quarantine|reject" $dmarcLive $status $true
    }
}

# ------------------------------ Output -------------------------------
# On-screen overview
$report | Format-Table Domain, Service, Type, Name, Status -AutoSize

# CSV export with timestamp
$csvPath = Join-Path $ExportFolder ("DomainDnsReport_{0:yyyyMMdd_HHmm}.csv" -f (Get-Date))
$report | Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8
Write-Host "Report saved to: $csvPath" -ForegroundColor Green

# Summary counts per status
Write-Host "`n----- Status summary -----" -ForegroundColor Cyan
$report | Group-Object { ($_.Status -split ' ')[0] } | Select-Object Name, Count | Format-Table -AutoSize

# Highlight required records that need attention
$issues = $report | Where-Object { ($_.Status -like "Missing*" -or $_.Status -like "Mismatch*") -and (-not $_.Optional) }
if ($issues) {
    Write-Host "Required records needing review:" -ForegroundColor Red
    $issues | Format-Table Domain, Type, Name, Expected, Live -AutoSize
} else {
    Write-Host "All required records match Microsoft 365 expectations." -ForegroundColor Green
}

# ----------------------------- Clean up ------------------------------
Disconnect-MgGraph | Out-Null

Featured Post

Hybrid Exchange: Why On-Prem App Emails Miss Cloud Mailboxes, and How RemoteMailbox Fixes It

Scope: hybrid Exchange (on-premises Exchange 2016/2019 + Exchange Online + Microsoft Entra Connect), where on-premises applications send m...

Popular posts