Saturday, November 21, 2026

Power Automate Desktop: Export Environment Variables Report (Key, Value, Used-By Flows) to CSV & Excel

Overview

  • Goal: list every environment variable in a solution, show its value, and name the cloud flows that use it
  • Output: EnvVar_Usage_Report_<Solution>_<yyyyMMdd_HHmmss>.csv and .xlsx in the Downloads folder
  • Why it helps:
    • Check configuration before/after a solution import (Dev → Test → Prod)
    • Find unused variables before cleaning up a solution
    • See which flows break if you change or delete a variable
  • How (one line): 2 Dataverse List rows actions (FetchXML) → loop and match → data table → Write to CSV file → Excel Save as .xlsx
  • No HTTP actions, app registrations or tokens: uses the built-in Microsoft Dataverse connector actions available in desktop flows

Prerequisites

ItemDetail
Power Automate for desktopInstalled and signed in to the target environment (v2 schema)
Microsoft Dataverse connectionUsed by List rows from selected environment; created from PAD's Connection references dialog
LicenseDataverse is a premium connector: desktop flows need an Attended RPA (Premium) license for premium connector actions
Microsoft ExcelOnly for the .xlsx output (remove the last 2 actions for CSV only)
A solution with environment variablesExample: EnvVar JSON Merge Demo with 4 variables
PermissionsRead access to environmentvariabledefinition, environmentvariablevalue, solution, solutioncomponent, workflow

Report output

  • One row per environment variable, 9 columns
ColumnSourceExample
Environment NameEnvironmentName variable (line 1)Default Environment
Solution Namesolution.friendlynameEnvVar JSON Merge Demo
Keyschemanamedemo_ConfigApp
Display NamedisplaynameConfig App
Typetype (formatted label)JSON
ValueCurrent value if set, else default value{"app":{"name":"DemoApp",...}}
Value SourceWhich value was usedDefault value / Current value / No value
Used By FlowsCloud flows whose definition references the variableMerge JSON Environment Variables
Flow CountNumber of those flows1

Sample output (CSV, shortened):

Environment Name,Solution Name,Key,Display Name,Type,Value,Value Source,Used By Flows,Flow Count
Default Environment,EnvVar JSON Merge Demo,demo_ConfigApp,Config App,JSON,"{""app"":{""name"":""DemoApp""}}",Default value,Merge JSON Environment Variables,1
Default Environment,EnvVar JSON Merge Demo,demo_ConfigEmail,Config Email,JSON,"{""email"":{""support"":""support@contoso.com""}}",Default value,Merge JSON Environment Variables,1
Default Environment,EnvVar JSON Merge Demo,demo_ConfigLimits,Config Limits,JSON,"{""limits"":{""maxItems"":100}}",Default value,Merge JSON Environment Variables,1
Default Environment,EnvVar JSON Merge Demo,demo_Env_not_using_key,Env_not_using_key,String,Env_not_using_value,Default value,Not used,0
  • JSON values are quoted and escaped, so Excel opens the file without breaking columns
  • Not used + 0 = no cloud flow references the variable (clean-up candidate)

How it works

Dataverse tableUsed for
environmentvariabledefinitionKey, display name, type, default value
environmentvariablevalueCurrent value (outer join, alias cv)
solutioncomponentLinks variables to a solution (componenttype = 380 = Environment Variable Definition)
solutionFilter by display name or unique name; returns display name (alias sol)
workflowAll cloud flows (category = 5) and their definitions (clientdata)
  1. Set inputs: environment name, solution name, output paths with timestamp
  2. Query 1 (FetchXML): variables in the solution + current value + solution display name
  3. Query 2 (FetchXML): every cloud flow in the environment with its definition
  4. Loop each variable:
    • Search each flow definition for (<schemaname>), which is how Power Automate stores a reference, e.g. "Config App (demo_ConfigApp)"
    • Collect matching flow names and a count
    • Pick current value → else default value → else "No value"
    • Add a row to the data table
  5. Write to CSV file (UTF-8, headers on)
  6. Launch Excel with the CSV (hidden) → Close and save as .xlsx

[ PHOTO 1 ]

Flow overview: FetchXML variables, two Dataverse List rows actions, data table and loops

Photo 1: Flow overview: FetchXML variables, two Dataverse List rows actions, data table and loops


[ PHOTO 2 ]

End of the flow: insert row, write to CSV file, launch Excel, close and save as .xlsx

Photo 2: End of the flow: insert row, write to CSV file, launch Excel, close and save as .xlsx

  • The solution filter uses <filter type="or"> on friendlyname and uniquename: pass either name
  • Flow usage is checked across the whole environment, so you also see flows outside the solution that depend on a variable

Step-by-step build

  • Fastest way: paste the full code (end of this post) into an empty flow, then link the connection

Step 1: Create the flow

  • Power Automate for desktop → New flow
  • Name: EnvVar Usage Report Desktop
  • Leave Power Fx enabled off (code uses classic %variable% syntax)

Step 2: Paste the actions

  • Copy the code from the PAD code section
  • Click the empty Main canvas → Ctrl+V
  • Result: 50 actions

[ PHOTO 3 ]

Lines 1–6 after pasting: inputs and output file paths

Photo 3: Lines 1–6 after pasting: inputs and output file paths

Step 3: Fix the two connection errors

  • The Errors list shows 2 errors on the List rows from selected environment actions (the connection ID in pasted code is tenant-specific)
  • For each of the two actions:
    • Double-click → Connection references
    • Pick your Microsoft Dataverse connection → Ok → Save
  • Environment stays (Current); the table name resolves automatically
  • 2 warnings remain (Dynamic output schema couldn't be retrieved): expected because the FetchXML comes from a variable; the flow runs fine

[ PHOTO 4 ]

Expected after paste: 2 connection errors in the Errors list

Photo 4: Expected after paste: 2 connection errors in the Errors list


[ PHOTO 5 ]

List rows from selected environment: Environment = (Current), fix via Connection references

Photo 5: List rows from selected environment: Environment = (Current), fix via Connection references

Step 4: Set your inputs

  • Line 1 → EnvironmentName (any label, e.g. Default Environment)
  • Line 2 → SolutionName: display name or unique name of your solution

Step 5: Save draft, Publish, Run

  • Save (= Save draft) → Publish → Run
  • Check Downloads for the .csv and .xlsx files

[ PHOTO 6 ]

Save (draft) and Publish are separate buttons: Publish is what console and cloud runs use

Photo 6: Save (draft) and Publish are separate buttons: Publish is what console and cloud runs use

Gotchas found while testing

ProblemCauseFix
Changes don't show when run from the console or a cloud flowWith version control, Save only saves a draft; console and cloud runs use the published versionAlways Save then Publish
Report still has old columns after pasting new codeNew actions pasted without deleting the old ones; both blocks ran, the old one lastClick an action → Ctrl+A → Delete → confirm 0 Actions → paste
"Connection with internal id ... not found" after pasteConnection ID in copied code is tenant-specificRe-link via Connection references on both List rows actions
Error reading cv.value or defaultvalueDataverse omits empty columns from the responseCheck with Contains(EnvVar, 'cv.value') before reading
Environment display name not availableNot stored in any Dataverse table desktop flows can query; organization.name returns the internal org nameKeep it as a variable on line 1
.xlsx step failsExcel not installedRemove the last 2 actions, keep CSV only

Thoughts and next steps

  • Desktop vs cloud: the same report works as a cloud flow (Dataverse List rows + Create CSV table + SharePoint Create file). Desktop = local file, no SharePoint/OneDrive dependency; cloud = scheduled runs and a shareable link
  • Usage detection is text-based: reliable for cloud flows, but it does not detect usage in canvas apps, Copilot Studio agents, plugins or desktop flows
  • Environment-wide scan is a feature: shows dependencies from flows outside the solution, which is exactly what breaks after a rename or delete
  • Large environments: List rows returns up to 5,000 rows by default; add FetchXML paging for more cloud flows
  • Secrets: never write Secret-type (Azure Key Vault) values to a file; mask them
  • Columns worth adding next:
    • Current Value and Default Value as separate columns
    • Missing Value flag
    • Flow status [On]/[Off]
    • Is Required and Is Managed
    • Report generated date/time
  • Make it an input: turn SolutionName into a desktop flow input variable so a cloud flow can pass it

PAD code (with comments)

  • Paste into an empty desktop flow (Main)
  • Lines starting with # are comments
  • The connection ID is a placeholder: re-link your own Dataverse connection after pasting (Step 3)
# ===== 1. INPUTS =====
# Label for the report (desktop flows can't read the environment display name from Dataverse)
SET EnvironmentName TO $'''Default Environment'''
# Solution display name OR unique name - both work (see the OR filter below)
SET SolutionName TO $'''EnvVar JSON Merge Demo'''
# ===== 2. OUTPUT FILE PATHS (Downloads folder + timestamp) =====
System.GetEnvironmentVariable.GetEnvironmentVariable Name: $'''USERPROFILE''' Value=> UserProfile
DateTime.GetCurrentDateTime.Local DateTimeFormat: DateTime.DateTimeFormat.DateAndTime CurrentDateTime=> CurrentDateTime
Text.ConvertDateTimeToText.FromCustomDateTime DateTime: CurrentDateTime CustomFormat: $'''yyyyMMdd_HHmmss''' Result=> RunStamp
SET CsvPath TO $'''%UserProfile%\\Downloads\\EnvVar_Usage_Report_%SolutionName%_%RunStamp%.csv'''
SET XlsxPath TO $'''%UserProfile%\\Downloads\\EnvVar_Usage_Report_%SolutionName%_%RunStamp%.xlsx'''
# ===== 3. FETCHXML QUERIES =====
# Query 1: env variable definitions in the solution (componenttype 380) + current value (alias cv) + solution display name (alias sol)
SET EnvVarFetchXml TO $'''<fetch><entity name=\"environmentvariabledefinition\"><attribute name=\"schemaname\" /><attribute name=\"displayname\" /><attribute name=\"type\" /><attribute name=\"defaultvalue\" /><order attribute=\"schemaname\" /><link-entity name=\"solutioncomponent\" from=\"objectid\" to=\"environmentvariabledefinitionid\" link-type=\"inner\"><filter><condition attribute=\"componenttype\" operator=\"eq\" value=\"380\" /></filter><link-entity name=\"solution\" from=\"solutionid\" to=\"solutionid\" link-type=\"inner\" alias=\"sol\"><attribute name=\"friendlyname\" /><filter type=\"or\"><condition attribute=\"friendlyname\" operator=\"eq\" value=\"%SolutionName%\" /><condition attribute=\"uniquename\" operator=\"eq\" value=\"%SolutionName%\" /></filter></link-entity></link-entity><link-entity name=\"environmentvariablevalue\" from=\"environmentvariabledefinitionid\" to=\"environmentvariabledefinitionid\" link-type=\"outer\" alias=\"cv\"><attribute name=\"value\" /></link-entity></entity></fetch>'''
# Query 2: all cloud flows (category 5) with their definition JSON (clientdata)
SET FlowFetchXml TO $'''<fetch><entity name=\"workflow\"><attribute name=\"name\" /><attribute name=\"clientdata\" /><filter><condition attribute=\"category\" operator=\"eq\" value=\"5\" /></filter></entity></fetch>'''
# ===== 4. RUN QUERIES (Dataverse > List rows from selected environment, Environment = Current) =====
# After pasting: re-link YOUR Microsoft Dataverse connection on both actions (Connection references)
@@organization: '(Current)'
@@entityName: 'Environment Variable Definitions'
@@connectionDisplayName: 'Microsoft Dataverse'
External.InvokeCloudConnector Connection: '00000000-0000-0000-0000-000000000000' ConnectorId: '/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps' OperationId: 'ListRecordsWithOrganization' @organization: $'''current''' @entityName: $'''environmentvariabledefinitions''' @fetchXml: EnvVarFetchXml @ListRecordsWithOrganizationResponse=> EnvVarResponse @ListRecordsWithOrganizationHeaders=> EnvVarHeaders
@@organization: '(Current)'
@@entityName: 'Processes'
@@connectionDisplayName: 'Microsoft Dataverse'
External.InvokeCloudConnector Connection: '00000000-0000-0000-0000-000000000000' ConnectorId: '/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps' OperationId: 'ListRecordsWithOrganization' @organization: $'''current''' @entityName: $'''workflows''' @fetchXml: FlowFetchXml @ListRecordsWithOrganizationResponse=> FlowResponse @ListRecordsWithOrganizationHeaders=> FlowHeaders
# ===== 5. REPORT TABLE (column headers) =====
Variables.CreateNewDatatable InputTable: { ^['Environment Name', 'Solution Name', 'Key', 'Display Name', 'Type', 'Value', 'Value Source', 'Used By Flows', 'Flow Count'] } DataTable=> ReportTable
# ===== 6. ONE ROW PER ENVIRONMENT VARIABLE =====
LOOP FOREACH EnvVar IN EnvVarResponse['value']
    SET UsedBy TO $''''''
    SET FlowCount TO 0
    # A flow definition stores each variable it uses as "Display Name (schemaname)"
    LOOP FOREACH CloudFlow IN FlowResponse['value']
        IF Contains(CloudFlow['clientdata'], $'''(%EnvVar['schemaname']%)''', False) THEN
            IF FlowCount > 0 THEN
                SET UsedBy TO $'''%UsedBy%; '''
            END
            SET UsedBy TO $'''%UsedBy%%CloudFlow['name']%'''
            Variables.IncreaseVariable Value: FlowCount IncrementValue: 1
        END
    END
    IF FlowCount = 0 THEN
        SET UsedBy TO $'''Not used'''
    END
    # Empty columns are left out of the Dataverse response, so check the key exists before reading it
    # Current value wins over default value
    IF Contains(EnvVar, $'''cv.value''', False) THEN
        SET EnvValue TO EnvVar['cv.value']
        SET ValueSource TO $'''Current value'''
    ELSE IF Contains(EnvVar, $'''defaultvalue''', False) THEN
        SET EnvValue TO EnvVar['defaultvalue']
        SET ValueSource TO $'''Default value'''
    ELSE
        SET EnvValue TO $''''''
        SET ValueSource TO $'''No value'''
    END
    # Use the readable type label (JSON, String...) when Dataverse returns it, else the option number
    SET EnvType TO EnvVar['type']
    IF Contains(EnvVar, $'''type@OData.Community.Display.V1.FormattedValue''', False) THEN
        SET EnvType TO EnvVar['type@OData.Community.Display.V1.FormattedValue']
    END
    # Solution display name from Dataverse (correct even when a unique name was passed in)
    SET RowSolutionName TO SolutionName
    IF Contains(EnvVar, $'''sol.friendlyname''', False) THEN
        SET RowSolutionName TO EnvVar['sol.friendlyname']
    END
    Variables.AddRowToDataTable.AppendRowToDataTable DataTable: ReportTable RowToAdd: [EnvironmentName, RowSolutionName, EnvVar['schemaname'], EnvVar['displayname'], EnvType, EnvValue, ValueSource, UsedBy, FlowCount]
END
# ===== 7. SAVE AS CSV, THEN CONVERT TO EXCEL =====
File.WriteToCSVFile.WriteCSV VariableToWrite: ReportTable CSVFile: CsvPath CsvFileEncoding: File.CSVEncoding.UTF8 IncludeColumnNames: True IfFileExists: File.IfFileExists.Overwrite ColumnsSeparator: File.CSVColumnsSeparator.SystemDefault
# Open the CSV in a hidden Excel and save it as .xlsx (remove these 2 actions if Excel isn't installed)
Excel.LaunchExcel.LaunchAndOpenUnderExistingProcess Path: CsvPath Visible: False ReadOnly: False Instance=> ExcelInstance
Excel.CloseExcel.CloseAndSaveAs Instance: ExcelInstance DocumentFormat: Excel.ExcelFormat.OpenXmlWorkbook DocumentPath: XlsxPath

References

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

Power Automate Desktop: Export Environment Variables Report (Key, Value, Used-By Flows) to CSV & Excel

Overview Goal: list every environment variable in a solution, show its value, and name the cloud flows that use it Output: EnvVar_Usage_Re...

Popular posts