Short answer: put your Exchange administrators in a security group, give that group an Exchange role in each customer’s GDAP relationship, then sign in as a named admin with MFA and connect to each customer with Connect-ExchangeOnline -DelegatedOrganization. DAP, MSOnline and Basic authentication remote PowerShell no longer work for this.
Last reviewed 8 October 2026 by Elliot Munro, CISO.
This guide replaces our older delegated admin scripts for Office 365 customer tenants. Those scripts used the retired MSOnline module, DAP and Basic authentication remote PowerShell. Everything below uses GDAP, named accounts with MFA and the current Exchange Online PowerShell module, and it links the tested method from our open-source GDAP partner toolkit.
A financial services client asked us why a new starter had stopped receiving some email after her sign-in name was changed. Our automated checks couldn’t help, because the client’s tenant required MFA that our automation’s token couldn’t satisfy. So a technician signed in the way this guide recommends, as a named admin with MFA through GDAP, and ran a message trace on both addresses. Nothing had failed inside the tenant. The real cause was outside senders holding onto an early bounce.
Signing in as a named admin through GDAP is the foundation of everything below. Our older scripts looped through every customer tenant with three pieces of plumbing: MSOnline listed the customers, DAP gave the access, and a Basic authentication remote PowerShell session connected to each tenant. All three have been retired or replaced. This guide shows the modern way to do the same work with granular delegated admin privileges (GDAP), first by hand with Connect-ExchangeOnline, then with the tested method from our open-source GDAP partner toolkit. It finishes with a read-only script that finds external mail forwarding in every customer you manage.
Not technical? Let us help
This article is written for IT teams at Microsoft partners. If you’re a business owner who wants to know whether anyone in your organisation is quietly forwarding email to an outside address, get in touch with us and we’ll check for you.
Who this is for
- Managed service providers and Cloud Solution Provider (CSP) partners who manage Microsoft 365 for customers through Partner Center.
- Technicians who need to run Exchange Online PowerShell in more than one customer tenant, for reporting or for planned changes.
- Anyone still holding on to a script that starts with
Connect-MsolService,Get-MsolPartnerContractorNew-PSSession ... -Authentication Basic.
If you only manage your own organisation, you don’t need GDAP. Run Connect-ExchangeOnline without the DelegatedOrganization parameter instead.
What changed
The Exchange cmdlets inside the old scripts (Get-Mailbox, Get-InboxRule, Set-Mailbox and so on) mostly still work. It’s the plumbing around them that broke.
| Old method | What happened | Use instead |
|---|---|---|
MSOnline module (Connect-MsolService, Get-MsolPartnerContract) |
Retired on 30 May 2025. Msol cmdlets no longer run. | Microsoft Graph PowerShell (Microsoft’s migration guidance) |
AzureAD module (Get-AzureADContract) |
Microsoft announced its retirement from mid-October 2025. | Microsoft Graph PowerShell |
| DAP (the Admin agents group with Global Administrator in every customer) | Being replaced by GDAP. DAP hasn’t been available with reseller relationships since 10 October 2023, and new customers have received default GDAP roles instead of DAP since late 2023. Where a customer has both, GDAP takes precedence. | GDAP relationships with only the roles you need |
Basic authentication remote PowerShell (New-PSSession to outlook.office365.com/powershell-liveid?DelegatedOrg=...) |
Basic authentication is off for remote PowerShell and can’t be turned back on. Remote PowerShell itself was disabled from 1 October 2023. | Connect-ExchangeOnline -DelegatedOrganization in the Exchange Online PowerShell module |
| “Allow-list your office IP so the script can skip MFA” | Microsoft’s partner security requirements say you must enforce MFA on every user account in your partner tenant, and partner users must complete MFA for admin on behalf of (AOBO) operations. Microsoft also began enforcing mandatory MFA for Microsoft 365 admin center sign-ins in February 2025. | Interactive sign-in with MFA for technicians. Workload identities (certificate-based apps) for unattended jobs. |
The good news: Microsoft confirms that Connect-ExchangeOnline with the DelegatedOrganization parameter works with GDAP. You sign in once as yourself, name the customer, and every cmdlet in that session runs against the customer’s organisation.
How GDAP access to Exchange Online works
A GDAP relationship is an agreement between your partner tenant and one customer tenant. It lists the Microsoft Entra roles you’re asking for and how long the access lasts. The customer has to approve it, the maximum duration is two years, and you can turn on auto extend to add six months at a time. Inside your own tenant, you then assign those roles to security groups, and you put named technicians in the groups. That replaces the standing Global Administrator access that DAP gave everyone in your Admin agents group.
When a technician in that group runs Connect-ExchangeOnline -DelegatedOrganization, Exchange Online maps their Microsoft Entra role to its own role groups. The mapping matters for least privilege:
- Exchange Administrator maps to the Organization Management role group, which can do almost anything in Exchange Online. Microsoft’s GDAP role guidance lists it for helpdesk tasks such as managing shared mailboxes, quota issues and transport rules.
- Global Reader maps to View-Only Organization Management. It looks like the obvious choice for a read-only report, but Microsoft documents that Get-InboxRule doesn’t work for the Global Reader role, so it can’t produce the inbox rule half of this report.
- Exchange Recipient Administrator maps to Recipient Management. It’s much narrower than Exchange Administrator. Microsoft’s feature permissions table lists Recipient Management alongside Organization Management for mailbox settings, so it’s the role to try first for this report.
The mappings come from Microsoft’s Permissions in Exchange Online page. Get-InboxRule needs a role that can manage mailbox settings. Exchange Recipient Administrator (Recipient Management) is narrower than Exchange Administrator, so this guide uses it first and falls back to Exchange Administrator only if your test in Step 5 fails. Both scripts accept either role. To see which roles include a cmdlet, connect and run Get-ManagementRole -Cmdlet Get-InboxRule as described in Find the permissions required to run any Exchange cmdlet.
Prerequisites
- A Microsoft partner tenant with GDAP relationships that your customers have approved.
- Someone with the Admin agent role in Partner Center to request relationships and assign roles to security groups. The technicians who run the scripts don’t need it. Microsoft’s GDAP FAQ recommends that people who manage customer tenants, but shouldn’t manage subscriptions, sit in GDAP security groups rather than the Admin agent role.
- One named account per technician in your partner tenant, with MFA enforced. No shared accounts.
- PowerShell 7 or Windows PowerShell 5.1. Microsoft recommends PowerShell 7 for the Microsoft Graph PowerShell SDK. Exchange Online PowerShell module versions 3.10.0 and later need PowerShell 7.6.0 or later, and all module versions are supported in Windows PowerShell 5.1. The execution policy must allow local scripts. If it doesn’t, run
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser. The toolkit method later in this guide needs PowerShell 7.4 or later (7.6 recommended) and doesn’t run in Windows PowerShell 5.1. - The ExchangeOnlineManagement, Microsoft.Graph.Authentication and Microsoft.Graph.Identity.Partner modules.
- Admin consent in your partner tenant for the Microsoft Graph DelegatedAdminRelationship.Read.All delegated permission. It’s only needed for the script that lists customers, and it requires admin consent. When the consent prompt appears, the admin should leave Consent on behalf of your organization unticked unless every technician needs it, or use a dedicated admin app with Assignment required? set to Yes, as described in our Microsoft Graph PowerShell guide.
Step-by-step: set up GDAP for Exchange Online PowerShell
Step 1: Create a security group for Exchange administration
- In the Microsoft Entra admin center for your partner tenant, signed in as a Groups Administrator (or another role that can create groups), create a security group with a clear name, for example GDAP Exchange Administrators.
- Add only the named technicians who need Exchange Online access across customers.
- Strongly recommended: manage the group with Privileged Identity Management (PIM) for Groups so technicians activate membership just in time instead of holding it permanently. Microsoft’s GDAP FAQ describes using PIM on GDAP security groups.
Step 2: Make sure each customer’s relationship includes an Exchange role
- Sign in to Partner Center as an Admin agent and select Customers.
- Select the customer, then Admin relationships, and check which Microsoft Entra roles the active relationship includes.
- If neither Exchange Recipient Administrator nor Exchange Administrator is there, select Request for new relationship, give it a unique name and a duration, choose Select Microsoft Entra roles, add Exchange Recipient Administrator (plus Exchange Administrator only if your service genuinely needs organisation-wide Exchange changes, and any other roles you need), and select Finalize request. You can’t add roles to an existing relationship, so a new request is the only way to add one.
- Send the request email to the customer. It only takes effect once they approve it.
Microsoft’s walkthrough is Obtain granular admin permissions to manage a customer’s service.
Step 3: Assign the Exchange role to your security group
- In Partner Center, select Customers, the customer, Admin relationships, and then the relationship.
- Under Security groups, select Add security groups, choose your GDAP Exchange Administrators group and select Next.
- Select Exchange Recipient Administrator (or Exchange Administrator, if that’s the role you need) and then Save. The status shows Pending, then Active after you refresh the page roughly 30 seconds later.
Microsoft notes that partners must explicitly grant permissions to security groups in the relationship before they can manage the customer. Partner Center shows a yellow warning icon next to relationships with no access assignments. See Grant granular permissions to security groups.
Step 4: Install the PowerShell modules
Run these in the version of PowerShell you’ll use for the scripts:
Install-Module -Name ExchangeOnlineManagement -Scope CurrentUser Install-Module -Name Microsoft.Graph.Authentication, Microsoft.Graph.Identity.Partner -Scope CurrentUser
If they’re already installed, run Update-Module -Name ExchangeOnlineManagement to pick up the latest release.
Step 5: Test one customer by hand
Before you loop through every customer, prove that the access works for one. Replace the account, customer domain and mailbox with your own:
Connect-ExchangeOnline -UserPrincipalName jane.smith@yourmsp.com.au -DelegatedOrganization customer.onmicrosoft.com # Proves the GDAP connection works Get-AcceptedDomain # Proves your role can read inbox rules (use any mailbox in the customer tenant) Get-InboxRule -Mailbox someone@customer.com.au Disconnect-ExchangeOnline -Confirm:$false
The DelegatedOrganization parameter accepts the customer’s primary .onmicrosoft.com domain or their tenant ID. If Get-AcceptedDomain returns the customer’s domains, your GDAP setup works. If Get-InboxRule also runs without an access error, your role is enough for the report. If it fails with Exchange Recipient Administrator, add Exchange Administrator to the relationship (Step 2) and assign it to your group (Step 3). You can confirm which roles include the cmdlet with Get-ManagementRole -Cmdlet Get-InboxRule. Microsoft suggests the same quick test in Connect to Exchange Online PowerShell.
Steps 6 and 7 and the two scripts below use only Microsoft’s modules. If you run Exchange Online PowerShell across customers regularly, the toolkit method later in this guide gets a token for each customer from one MFA sign-in, without a sign-in prompt for every tenant.
Step 6: Build the customer list from your GDAP relationships
The old scripts used Get-MsolPartnerContract to list customers. There are two Microsoft Graph replacements, and they answer different questions:
- Get-MgContract lists the partnerships recorded in your partner tenant (CSP, Office 365 Syndication or Advisor) and returns each customer’s ID and default domain. It needs Directory.Read.All. Its documentation doesn’t mention GDAP, and it can’t tell you whether you hold an active GDAP relationship or which roles it includes.
- Get-MgTenantRelationshipDelegatedAdminRelationship lists your GDAP relationships, including each customer’s tenant ID, the relationship status and the role IDs it grants. It needs only DelegatedAdminRelationship.Read.All.
Because the question is “which customers can I run Exchange Online PowerShell against?”, the first script below uses the GDAP relationships API. It keeps relationships whose status is active and that include Exchange Recipient Administrator (template ID 31392ffb-586c-42d1-9346-e59415a2cc4e) or Exchange Administrator (template ID 29232cdf-9323-42fd-ade2-1d097af3e4de), then saves one row per customer to a CSV file. A relationship that includes the role doesn’t prove your group was assigned it, so Script 2 records any customer it can’t reach in its errors file. Since the DelegatedOrganization parameter accepts a tenant ID, you don’t need each customer’s domain name.
Step 7: Run the report in a new PowerShell window
Run the second script in a fresh PowerShell window rather than the one you used for Microsoft Graph. Microsoft notes that the Exchange Online module can conflict with other modules already loaded in the same session, which shows up as a System.IdentityModel.Tokens.Jwt assembly error. Keeping the two steps in separate windows avoids that, and it also means a technician without Graph consent can run the report from a CSV that someone else produced.
Script 1: Export customers with Exchange admin access
Save this as Export-GdapExchangeCustomers.ps1.
#Requires -Version 5.1
<#
.SYNOPSIS
Lists the customers where your partner tenant has an active GDAP relationship
that includes Exchange Recipient Administrator or Exchange Administrator,
and saves them to a CSV file.
.DESCRIPTION
Read-only. Signs in to YOUR partner tenant with your own named account (MFA)
and reads GDAP relationships through Microsoft Graph using the
DelegatedAdminRelationship.Read.All delegated permission.
Run this script in its own PowerShell window. Then open a NEW PowerShell
window and run Get-GdapExternalForwardingReport.ps1 against the CSV.
.NOTES
Author: Elliot Munro - GCIT (https://gcit.com.au)
Updated: October 2026
Article: https://gcit.com.au/knowledge-base/gdap-exchange-online-powershell-customer-tenants/
#>
[CmdletBinding()]
param(
# Your own profile folder, so other users of the computer can't read or change the file
[string]$OutputPath = "$env:USERPROFILE\GdapExchange\GdapExchangeCustomers.csv",
[int]$ExpiryWarningDays = 30
)
$ErrorActionPreference = "Stop"
# Template IDs of the built-in Exchange roles in Microsoft Entra ID
$exchangeRoleIds = @(
"31392ffb-586c-42d1-9346-e59415a2cc4e" # Exchange Recipient Administrator
"29232cdf-9323-42fd-ade2-1d097af3e4de" # Exchange Administrator
)
Import-Module Microsoft.Graph.Identity.Partner
# Delegated sign-in to your partner tenant. Expect an MFA prompt.
Connect-MgGraph -Scopes "DelegatedAdminRelationship.Read.All" -ContextScope Process -NoWelcome
try {
$relationships = @(Get-MgTenantRelationshipDelegatedAdminRelationship -All)
Write-Host "Found $($relationships.Count) GDAP relationship(s) in total." -ForegroundColor Cyan
# Keep only active relationships that include one of the Exchange roles
$exchangeRelationships = @($relationships | Where-Object {
$_.Status -eq "active" -and
@($_.AccessDetails.UnifiedRoles.RoleDefinitionId | Where-Object { $_ -in $exchangeRoleIds }).Count -gt 0
})
# A customer can have more than one relationship, so keep one row per tenant
$customers = @($exchangeRelationships |
Sort-Object -Property @{ Expression = { $_.Customer.TenantId } } -Unique |
ForEach-Object {
[pscustomobject]@{
TenantId = $_.Customer.TenantId
DisplayName = $_.Customer.DisplayName
RelationshipName = $_.DisplayName
EndDateTime = $_.EndDateTime
}
} |
Sort-Object -Property DisplayName)
if ($customers.Count -eq 0) {
Write-Warning "No active GDAP relationships include Exchange Recipient Administrator or Exchange Administrator."
return
}
New-Item -ItemType Directory -Path (Split-Path -Path $OutputPath -Parent) -Force | Out-Null
$customers | Export-Csv -Path $OutputPath -NoTypeInformation -Encoding UTF8
Write-Host "Saved $($customers.Count) customer(s) to $OutputPath" -ForegroundColor Green
# Flag relationships that are about to expire so access doesn't lapse mid-incident
$expiryCutoff = (Get-Date).AddDays($ExpiryWarningDays)
$customers |
Where-Object { $_.EndDateTime -and ([datetime]$_.EndDateTime) -lt $expiryCutoff } |
ForEach-Object {
Write-Warning "$($_.DisplayName): relationship '$($_.RelationshipName)' ends $($_.EndDateTime)"
}
}
finally {
Disconnect-MgGraph | Out-Null
}
Script 2: Find external mail forwarding in every customer tenant
Save this as Get-GdapExternalForwardingReport.ps1. It replaces our older articles on finding external forwarding mailboxes and inbox rules in customer tenants, and checks three things in one pass:
- Mailbox forwarding to an external SMTP address (ForwardingSmtpAddress).
- Mailbox forwarding to a recipient object such as a mail contact (ForwardingAddress), which the old scripts missed.
- Inbox rules that forward, forward as an attachment or redirect messages (ForwardTo, ForwardAsAttachmentTo and RedirectTo), including hidden rules.
An address counts as external when its domain isn’t one of the customer’s accepted domains. The script only reads. It doesn’t change or remove anything.
#Requires -Version 5.1
#Requires -Modules ExchangeOnlineManagement
<#
.SYNOPSIS
Read-only report of external mail forwarding across GDAP customer tenants.
.DESCRIPTION
For each customer in the input CSV (columns TenantId and DisplayName), this
script connects to Exchange Online with Connect-ExchangeOnline
-DelegatedOrganization and reports:
- Mailboxes whose ForwardingSmtpAddress or ForwardingAddress points
outside the customer's accepted domains
- Inbox rules that forward, forward as attachment or redirect mail to
addresses outside the customer's accepted domains
Nothing is changed in any tenant. Customers you can't reach (no active
GDAP relationship, no Exchange role assignment, or another error)
are written to a separate errors CSV and the script moves on.
.NOTES
Author: Elliot Munro - GCIT (https://gcit.com.au)
Updated: October 2026
Article: https://gcit.com.au/knowledge-base/gdap-exchange-online-powershell-customer-tenants/
Replaces the older GCIT scripts that used MSOnline, DAP and Basic
authentication remote PowerShell sessions.
#>
[CmdletBinding()]
param(
# Your own named partner account, for example jane.smith@yourmsp.com.au
[Parameter(Mandatory = $true)]
[string]$UserPrincipalName,
[string]$CustomerCsv = "$env:USERPROFILE\GdapExchange\GdapExchangeCustomers.csv",
[string]$OutputFolder = "$env:USERPROFILE\GdapExchange"
)
$ErrorActionPreference = "Stop"
$emailPattern = "[A-Za-z0-9._%+'-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"
function Get-SmtpAddress {
# Pulls plain email addresses out of values such as "smtp:user@domain" or
# "Display Name [SMTP:user@domain]"
param([object[]]$Value)
foreach ($item in $Value) {
if ($null -ne $item) {
foreach ($match in [regex]::Matches([string]$item, $emailPattern)) {
$match.Value.ToLowerInvariant()
}
}
}
}
function Test-ExternalAddress {
# Exact match only, so a subdomain of an accepted domain is reported as external.
# That errs on the side of showing you more, not less.
param([string]$Address, [string[]]$AcceptedDomain)
$domain = ($Address -split "@")[-1].ToLowerInvariant()
return (-not ($AcceptedDomain -contains $domain))
}
function New-Finding {
param($Customer, $Mailbox, [string]$Type, [string]$Target, $KeepsCopy, [string]$RuleName, $RuleEnabled)
[pscustomobject]@{
Customer = $Customer.DisplayName
TenantId = $Customer.TenantId
Mailbox = $Mailbox.UserPrincipalName
MailboxType = $Mailbox.RecipientTypeDetails
ForwardType = $Type
ExternalTo = $Target
KeepsCopy = $KeepsCopy
InboxRuleName = $RuleName
RuleEnabled = $RuleEnabled
}
}
$customers = @(Import-Csv -Path $CustomerCsv)
if ($customers.Count -eq 0 -or -not ($customers[0].PSObject.Properties.Name -contains "TenantId")) {
throw "The CSV must contain a TenantId column and at least one row."
}
New-Item -ItemType Directory -Path $OutputFolder -Force | Out-Null
$runStamp = Get-Date -Format "yyyyMMdd-HHmm"
$findingsPath = Join-Path -Path $OutputFolder -ChildPath "ExternalForwarding-$runStamp.csv"
$errorsPath = Join-Path -Path $OutputFolder -ChildPath "ExternalForwarding-Errors-$runStamp.csv"
$findings = [System.Collections.Generic.List[object]]::new()
$failures = [System.Collections.Generic.List[object]]::new()
$counter = 0
foreach ($customer in $customers) {
$counter++
Write-Host "[$counter/$($customers.Count)] $($customer.DisplayName)" -ForegroundColor Cyan
try {
# The tenant ID (or the primary .onmicrosoft.com domain) identifies the customer
Connect-ExchangeOnline -UserPrincipalName $UserPrincipalName -DelegatedOrganization $customer.TenantId -ShowBanner:$false
$acceptedDomains = @(Get-AcceptedDomain | ForEach-Object { ([string]$_.DomainName).ToLowerInvariant() })
$mailboxes = @(Get-EXOMailbox -ResultSize Unlimited -Properties ForwardingSmtpAddress, ForwardingAddress, DeliverToMailboxAndForward)
foreach ($mailbox in $mailboxes) {
# 1. Mailbox forwarding set to an SMTP address
foreach ($address in @(Get-SmtpAddress -Value $mailbox.ForwardingSmtpAddress)) {
if (Test-ExternalAddress -Address $address -AcceptedDomain $acceptedDomains) {
$findings.Add((New-Finding -Customer $customer -Mailbox $mailbox -Type "Mailbox forwarding (ForwardingSmtpAddress)" -Target $address -KeepsCopy $mailbox.DeliverToMailboxAndForward -RuleName "" -RuleEnabled ""))
}
}
# 2. Mailbox forwarding set to a recipient object, such as a mail contact
if ($mailbox.ForwardingAddress) {
try {
$recipient = Get-Recipient -Identity ([string]$mailbox.ForwardingAddress)
$recipientAddresses = @(Get-SmtpAddress -Value @($recipient.PrimarySmtpAddress, $recipient.ExternalEmailAddress) | Select-Object -Unique)
foreach ($address in $recipientAddresses) {
if (Test-ExternalAddress -Address $address -AcceptedDomain $acceptedDomains) {
$findings.Add((New-Finding -Customer $customer -Mailbox $mailbox -Type "Mailbox forwarding (ForwardingAddress)" -Target $address -KeepsCopy $mailbox.DeliverToMailboxAndForward -RuleName "" -RuleEnabled ""))
}
}
}
catch {
$findings.Add((New-Finding -Customer $customer -Mailbox $mailbox -Type "Mailbox forwarding (ForwardingAddress, not resolved, check manually)" -Target ([string]$mailbox.ForwardingAddress) -KeepsCopy $mailbox.DeliverToMailboxAndForward -RuleName "" -RuleEnabled ""))
}
}
# 3. Inbox rules that forward or redirect mail
try {
$rules = @(Get-InboxRule -Mailbox $mailbox.UserPrincipalName -IncludeHidden)
}
catch {
$failures.Add([pscustomobject]@{
Customer = $customer.DisplayName
TenantId = $customer.TenantId
Stage = "Get-InboxRule for $($mailbox.UserPrincipalName)"
Error = $_.Exception.Message
})
continue
}
foreach ($rule in $rules) {
$ruleTargets = @(Get-SmtpAddress -Value (@($rule.ForwardTo) + @($rule.ForwardAsAttachmentTo) + @($rule.RedirectTo)) | Select-Object -Unique)
foreach ($address in $ruleTargets) {
if (Test-ExternalAddress -Address $address -AcceptedDomain $acceptedDomains) {
$findings.Add((New-Finding -Customer $customer -Mailbox $mailbox -Type "Inbox rule" -Target $address -KeepsCopy "" -RuleName $rule.Name -RuleEnabled $rule.Enabled))
}
}
}
}
Write-Host " Checked $($mailboxes.Count) mailbox(es)" -ForegroundColor Green
}
catch {
# Most often: no active GDAP relationship with an Exchange role for this
# customer, or your account isn't in the security group assigned that role
Write-Warning " Skipped $($customer.DisplayName): $($_.Exception.Message)"
$failures.Add([pscustomobject]@{
Customer = $customer.DisplayName
TenantId = $customer.TenantId
Stage = "Connect or tenant query"
Error = $_.Exception.Message
})
}
finally {
Disconnect-ExchangeOnline -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
}
}
Write-Host ""
# Only write a file when there is something in it
if ($findings.Count -gt 0) {
$findings | Export-Csv -Path $findingsPath -NoTypeInformation -Encoding UTF8
Write-Host "External forwarding found: $($findings.Count). Saved to $findingsPath" -ForegroundColor Yellow
}
else {
Write-Host "No external forwarding found in the customers that were checked." -ForegroundColor Green
}
if ($failures.Count -gt 0) {
$failures | Export-Csv -Path $errorsPath -NoTypeInformation -Encoding UTF8
Write-Host "Customers or mailboxes with errors: $($failures.Count). Saved to $errorsPath" -ForegroundColor Yellow
}
else {
Write-Host "Every customer and mailbox was checked without errors." -ForegroundColor Green
}
How to run it
- Save both scripts to a folder in your own user profile on your admin workstation, for example
%USERPROFILE%\Scripts\GDAP. Avoid a new folder directly under C:\, because every signed-in user can change files there, and a tampered script would run with your GDAP access. - Open PowerShell, change to that folder and run
.\Export-GdapExchangeCustomers.ps1. Sign in with your own partner account and complete the MFA prompt. The customer list is saved toGdapExchange\GdapExchangeCustomers.csvin your user profile folder ($env:USERPROFILE) by default, where other users of the computer can’t read or change it. Any relationship ending within 30 days is shown as a warning. - Open the CSV and remove any customers you don’t want to include in this run.
- Open a new PowerShell window and run
.\Get-GdapExternalForwardingReport.ps1 -UserPrincipalName jane.smith@yourmsp.com.auwith your own account. Depending on your sign-in session, you might be asked to authenticate more than once. - When it finishes, review the files in the same
GdapExchangefolder:ExternalForwarding-<date>.csvlists every external forward found, andExternalForwarding-Errors-<date>.csvlists customers or mailboxes that couldn’t be checked and why. Each file is only written when it has rows, and the summary at the end tells you which ones exist.
If you’d rather not use Microsoft Graph at all, create the CSV by hand with TenantId and DisplayName columns and skip straight to the report.
What to do with the results
- Treat every unexpected external forward as a possible account compromise until you’ve confirmed it with the customer. Microsoft notes that users can set up external forwarding rules deliberately or as a result of a compromised account. Our guide on how to detect a breach in Microsoft 365 covers the next steps.
- Check each customer’s outbound spam filter policy. Microsoft says the default Automatic - System-controlled setting can behave differently between organisations, and recommends setting Off - Forwarding is disabled or On - Forwarding is enabled explicitly. Turning it off blocks inbox rules and mailbox forwarding to external addresses, while forwarding between internal users isn’t affected. See Control external email forwarding.
- Where a customer has a genuine business reason to forward externally, allow it only for the users who need it, and record the approval.
Reusing the loop for other Exchange tasks
Most of the old delegated scripts (winmail.dat fixes, disabling POP and IMAP, calendar permissions, trusted senders, shared mailbox licensing checks) can be rebuilt on Script 2. Keep the connect, error handling and disconnect structure, and replace the code inside the try block. For anything that changes settings, build the script with [CmdletBinding(SupportsShouldProcess)], wrap each change in $PSCmdlet.ShouldProcess() and run it with -WhatIf against one customer before you run it for real. Get the customer’s approval for the change, and log what you changed in your ticketing system. Use the role that the change actually needs, which for organisation-wide settings such as POP and IMAP defaults is usually Exchange Administrator.
The tested method: our open-source GDAP partner toolkit
Scripts 1 and 2 use only Microsoft’s own modules, and Script 2 signs you in to each customer separately. For day-to-day work across many customers we built MspGdap, a free PowerShell module published on GitHub as our GDAP partner toolkit (MIT licence). It does the same job through supported Microsoft identity platform and Partner Center REST endpoints. It was tested live on 7 October 2026 against a Microsoft partner tenant and a GDAP customer: app creation, technician token registration, Partner Center pre-consent, Microsoft Graph, Exchange Online and Security and Compliance PowerShell with delegated GDAP tokens.
How it works:
- One multi-tenant partner app with a certificate credential.
New-MspPartnerAppcreates it once in your partner tenant, with delegated permissions only and no client secret (02 Create the partner app). - One refresh token per technician, kept in a SecretManagement vault. Each technician signs in once with MFA (
Register-MspPartnerToken). The token goes straight into a Microsoft.PowerShell.SecretManagement vault (SecretStore on the workstation, or Azure Key Vault) and is rewritten every time Microsoft rotates it. On its own it’s useless, because every use also needs the partner app’s certificate (03 Register a technician token). - Partner Center pre-consent.
Grant-MspPartnerAppConsentconsents the partner app into a GDAP customer through the Partner Center application consent API, one resource per request, then confirms each grant through Microsoft Graph. Nobody at the customer has to click a consent prompt. The technician needs Cloud Application Administrator or Application Administrator in that customer through GDAP (04 Pre-consent customers). - GDAP is still the ceiling. Every token acts as the technician, so the roles your security group holds in that customer decide what works, exactly as in Steps 1 to 3.
Connect-MspExchangeOnlinegets an Exchange Online token for the customer, connects withConnect-ExchangeOnlineusing AccessToken and DelegatedOrganization, checks the session landed in the tenant you asked for, and closes other Exchange sessions first so a command can’t run in the previous customer.
The short version, with your own values in place of the placeholders. Create the partner app first, as described in 02 Create the partner app.
# Once per workstation, from a clone of the repository (PowerShell 7.4 or later) Install-Module -Name Microsoft.PowerShell.SecretManagement, Microsoft.PowerShell.SecretStore -Repository PSGallery -Scope CurrentUser Register-SecretVault -Name 'MspGdap' -ModuleName 'Microsoft.PowerShell.SecretStore' Import-Module ./src/MspGdap/MspGdap.psd1 Set-MspConfiguration -PartnerTenantId '<PartnerTenantId>' -AppId '<PartnerAppId>' -CertificateThumbprint '<Thumbprint>' -VaultName 'MspGdap' # Once per technician (and again if the token is revoked or unused for 90 days) Register-MspPartnerToken -UserPrincipalName 'jane.admin@yourmsp.com.au' -SetAsDefault # Once per customer: pre-consent the partner app through Partner Center, then check it Grant-MspPartnerAppConsent -TenantId 'customer.onmicrosoft.com' -ManifestPath ./manifests/partner-app.minimal.json -WhatIf Grant-MspPartnerAppConsent -TenantId 'customer.onmicrosoft.com' -ManifestPath ./manifests/partner-app.minimal.json Test-MspPartnerAppConsent -TenantId 'customer.onmicrosoft.com' -ManifestPath ./manifests/partner-app.minimal.json # Every day: work in a customer's Exchange Online Connect-MspExchangeOnline -TenantId 'customer.onmicrosoft.com' Get-AcceptedDomain Disconnect-Msp
The toolkit’s find-external-forwarding.ps1 is the toolkit version of Script 2. It checks mailbox forwarding by default, and inbox rules as well with IncludeInboxRules. It only reads:
./scripts/exchange/find-external-forwarding.ps1 -TenantId 'customer.onmicrosoft.com' -IncludeInboxRules ./scripts/exchange/find-external-forwarding.ps1 -AllCustomers -IncludeInboxRules -OutputPath "$env:USERPROFILE\GdapExchange\ExternalForwarding.csv"
Before you rely on it:
- The toolkit needs PowerShell 7.4 or later (7.6 recommended) and ExchangeOnlineManagement 3.1.0 or later. Module versions 3.10.0 and later need PowerShell 7.6.
- Microsoft documents the AccessToken plus DelegatedOrganization combination only briefly. It worked in our live test, but run the connection against one customer again after each module upgrade.
- The role caveat from Step 5 still applies. Prove that Get-InboxRule works with Exchange Recipient Administrator in one customer before you run inbox rule checks across all of them, and fall back to Exchange Administrator only if it doesn’t.
- The repository’s rewritten scripts are checked automatically and have mocked tests, but most haven’t been run against a live tenant. Run each one against a single low-risk customer first.
The repository’s guides cover each step in full: 01 Prerequisites, 02 Create the partner app, 03 Register a technician token, 04 Pre-consent customers and 05 Exchange access. Its scripts folder maps our older knowledge base scripts to their GDAP rewrites.
Troubleshooting
- Some customers appear in the errors CSV with a connection error. Check in Partner Center that the customer has an active relationship that includes Exchange Recipient Administrator or Exchange Administrator, that your security group is assigned that role in the relationship, and that your account is a member of the group (or has activated it in PIM).
- Get-InboxRule fails for every mailbox in a customer. Your access in that tenant probably comes from Global Reader, which Get-InboxRule doesn’t work with, or Exchange Recipient Administrator wasn’t enough in your test. Assign Exchange Administrator to your group in that relationship and run the report again.
- Script 1 asks for admin approval. DelegatedAdminRelationship.Read.All requires admin consent. Ask an administrator in your partner tenant who can grant tenant-wide consent, or build the CSV by hand.
- Script 1 finds no customers. None of your active relationships include Exchange Recipient Administrator or Exchange Administrator. Check the roles on each relationship in Partner Center. Relationships that have expired or been terminated are ignored.
- “Could not load file or assembly ‘System.IdentityModel.Tokens.Jwt'”. Another module in the session is conflicting with the Exchange Online module. Close the window and run the report in a new PowerShell window.
- Sign-in errors that mention Web Account Manager (WAM). In module version 3.7.2 or later you can add the DisableWAM switch to Connect-ExchangeOnline.
- The module won’t load in PowerShell 7. Module versions 3.10.0 and later need PowerShell 7.6.0 or later. Update PowerShell, or use Windows PowerShell 5.1.
- Connect and disconnect commands fail for one technician only. Microsoft notes they’re likely to fail when the account’s profile path contains special PowerShell characters such as
$. - A technician with a guest account in the customer tenant can’t connect. Guest accounts don’t work with GDAP. The customer needs to remove the guest account.
- Grant-MspPartnerAppConsent fails for a customer. Check that your GDAP role in that customer includes Cloud Application Administrator or Application Administrator, and that your token came from an MFA sign-in. Calls to Partner Center also need the person running consent to be in your partner tenant’s AdminAgents group, so keep consent with the few people who hold it. 04 Pre-consent customers lists the common errors.
- The toolkit can’t get a token for one customer, or the customer’s Conditional Access blocks it. Our own automation hit a block like this in the story at the top of this guide. Connect interactively with
Connect-ExchangeOnline -UserPrincipalNameand DelegatedOrganization, as in Step 5, and review the policy with the customer.
Important notes
What not to do
- Don’t share admin accounts. Every technician signs in as themselves with MFA, so every action in a customer tenant traces back to a named person.
- Don’t create admin accounts in customer tenants to run your scripts. GDAP exists so you don’t need them, and every extra privileged account in a customer tenant is one more thing an attacker can steal.
- Don’t assume Default GDAP is least privilege. Customers you create in Partner Center get a Default GDAP relationship that includes powerful roles such as Privileged Role Administrator and Privileged Authentication Administrator (see the GDAP FAQ). Assign only the roles each security group needs, and replace the default relationship with a narrower one when you can.
- Don’t request Global Administrator as your default GDAP role. Microsoft recommends least-privileged roles by task, and a time-bound Global Administrator role only when you need to work around a known issue. Relationships that include Global Administrator can’t be auto extended.
- Don’t bypass MFA with IP allow-lists, app passwords or stored credentials. Microsoft says not to use the Credential parameter on Connect-ExchangeOnline for accounts that use MFA, which is exactly why the old scripts pushed people to weaken MFA.
- Don’t put every technician in the Admin agents group. Keep Admin agent for the few people who manage relationships in Partner Center.
- Don’t rebuild these scripts on the Partner Center PowerShell module. It was a community project that Microsoft never officially supported, and its documentation is archived.
Unattended automation
The scripts in this guide are for a technician running them interactively. For scheduled jobs, don’t put a user account in a script. Microsoft’s app-only authentication guide covers a multitenant app registration with the Exchange.ManageAsApp permission. For customer tenants, it needs admin consent and a role assignment in each customer tenant, and it signs in with a certificate that you can keep in Azure Key Vault. Microsoft notes that managed identities and service principals aren’t affected by mandatory MFA, which is why workload identities, not user accounts, are the right fit for automation. App-only access sits outside GDAP’s time limits and security groups, so give the app a read-only custom role group in each customer (for example one containing only the View-Only Recipients role), never Exchange Administrator. Our Exchange Online PowerShell guide shows how to set up that role group. Microsoft’s page also recommends GDAP with app consent for delegated scenarios, but the sample it links to relies on the archived Partner Center PowerShell module. Our toolkit builds that flow with supported REST calls instead, as described in the toolkit section above. For app-only Exchange access, its Enable-MspExchangeAppAccess command gives a separate automation app the Exchange.ManageAsApp permission and a Microsoft Entra role in each customer, then reads every change back. Use -Role 'Global Reader' for read-only jobs. That command wasn’t part of the 7 October 2026 live test, so try it on one customer first (05 Exchange access). Our GDAP Secure Application Model guide explains when to choose app-only access.
Handling the report safely
- The output CSV files contain customers’ email addresses and forwarding destinations. Store them somewhere with restricted access, attach them to the relevant ticket, and delete local copies once you’ve finished.
- The report doesn’t cover mail flow rules (transport rules). It also only flags inbox rule targets that include a visible SMTP address, so a rule that points at a directory object (for example a mail contact) won’t appear. For a second view, use the Auto forwarded messages report in the Exchange admin center.
- Get-InboxRule runs once per mailbox, so customers with many mailboxes take longer. Run large tenants on their own by trimming the CSV.
- An address is treated as internal only when its domain exactly matches one of the customer’s accepted domains. Forwarding to a subdomain (for example
mail.contoso.com.auwhen onlycontoso.com.auis accepted) is reported as external, so check those entries by eye before raising an alarm.
Related resources
Microsoft Learn
- Connect to Exchange Online PowerShell (including customer organisations with GDAP)
- Connect-ExchangeOnline cmdlet reference
- Granular delegated admin privileges (GDAP) introduction
- GDAP frequently asked questions
- GDAP role guidance (least-privileged roles by task)
- GDAP API overview in Microsoft Graph
- Permissions in Exchange Online
- Partner security requirements
- Control external email forwarding
GCIT GDAP partner toolkit (GitHub)
- MspGdap: GDAP partner toolkit for Microsoft partners (README, threat model and quick start)
- 04 Pre-consent customers and 05 Exchange access
- find-external-forwarding.ps1 and the other scripts folder rewrites
From the GCIT knowledge base
- How to detect a breach in Microsoft 365
- What to do if you clicked a phishing link
- Export customers’ Microsoft Secure Scores to CSV and HTML reports (another GDAP multi-tenant script)
- GDAP Secure Application Model: unattended MSP automation with Microsoft Graph
- How to connect to Exchange Online PowerShell
Need a hand with GDAP or Exchange Online?
GCIT manages Microsoft 365 for more than 300 organisations from the Gold Coast. If you’d like help moving your scripts to GDAP, auditing external forwarding across your tenants, or locking down partner access, contact our team.