Listen to this Post

Introduction:
Shared mailboxes are the backbone of collaborative workflows in Microsoft 365, yet they represent one of the most overlooked security blind spots in Exchange Online. When multiple users can send as, send on behalf of, or fully access a shared mailbox, the attack surface expands dramatically—and without a consolidated view of who holds these keys, organizations remain vulnerable to insider threats, credential misuse, and compliance violations. This article dissects a powerful PowerShell automation that consolidates Full Access, Send As, and Send on Behalf permissions into a single, actionable report, transforming a tedious manual audit into a streamlined security control.
Learning Objectives:
- Master the PowerShell commands to extract Full Access, Send As, and Send on Behalf permissions for any shared mailbox in Exchange Online.
- Implement a tenant-wide auditing strategy to identify unauthorized or excessive delegations across all shared mailboxes.
- Apply security best practices to lock down shared mailbox permissions and mitigate common delegation risks.
You Should Know:
- Understanding Shared Mailbox Delegation: The Three Permission Types
Before diving into the script, it’s critical to understand what each permission actually allows—and why the distinction matters for security.
- Full Access – Grants the delegate the ability to open, view, modify, and delete content within the shared mailbox. This permission does not allow sending emails. It is the most permissive access right and effectively makes the delegate an owner of the mailbox contents.
- Send As – Allows the delegate to send emails that appear to come directly from the shared mailbox address. Recipients have no indication that the email was sent by a delegate, making this a high-risk permission for impersonation attacks.
- Send on Behalf – Permits the delegate to send emails on behalf of the shared mailbox. Recipients will see the sender address formatted as “Delegate on behalf of SharedMailbox,” providing transparency but still carrying reputational risk.
The core challenge is that these three permissions are retrieved using different PowerShell cmdlets: `Get-MailboxPermission` for Full Access, `Get-RecipientPermission` for Send As, and the `GrantSendOnBehalfTo` property from `Get-Mailbox` for Send on Behalf. Manually running each cmdlet and correlating results is error-prone and time-consuming—exactly why automation is essential.
- The Script That Changes Everything: Auditing a Single Shared Mailbox
Hitendra Bhadoria’s PowerShell script provides an elegant solution for a single shared mailbox audit. Here’s the complete script with a breakdown of each component:
$m = "[email protected]" $fa = (Get-MailboxPermission $m | ? {$<em>.AccessRights -like "FullAccess" -and !$</em>.IsInherited}).User $sa = (Get-RecipientPermission $m | ? {$_.AccessRights -like "SendAs"}).Trustee $sob = (Get-Mailbox $m).GrantSendOnBehalfTo $users = $fa + $sa + $sob | Sort-Object -Unique $users | ForEach-Object { [bash]@{ User = $_ FullAccess = if ($fa -contains $<em>) {"Yes"} else {"No"} SendAs = if ($sa -contains $</em>) {"Yes"} else {"No"} SendOnBehalf = if ($sob -contains $_) {"Yes"} else {"No"} } } | Format-Table -AutoSize
Step‑by‑step breakdown:
- Define the target mailbox – Set `$m` to the primary SMTP address of the shared mailbox you wish to audit.
- Extract Full Access permissions – `Get-MailboxPermission $m` retrieves all permissions on the mailbox. The `Where-Object` filter (
?) keeps only entries where `AccessRights` contains “FullAccess” and the permission is not inherited (!$_.IsInherited). This excludes the default “SELF” permission and inherited entries from parent objects, focusing only on explicitly assigned delegates. The `.User` property extracts the delegate identities. - Extract Send As permissions – `Get-RecipientPermission $m` fetches Send As delegations. The filter `-like “SendAs”` isolates the correct permission type, and `.Trustee` extracts the delegate.
- Extract Send on Behalf permissions – `(Get-Mailbox $m).GrantSendOnBehalfTo` directly retrieves the list of users granted Send on Behalf rights from the mailbox object.
- Consolidate and deduplicate – The three arrays are concatenated and piped to `Sort-Object -Unique` to produce a single list of unique users.
- Build the report – For each unique user, the script constructs a custom object with boolean indicators for each permission type, then outputs a formatted table.
When to use this script: Access reviews, security audits, shared mailbox ownership validation, troubleshooting delegation issues, and migration or tenant consolidation projects.
- Going Tenant-Wide: Auditing Every Shared Mailbox in Your Organization
While the single-mailbox script is invaluable for targeted investigations, security-conscious administrators need a tenant-wide view. The extended script from o365reports.com addresses this requirement by iterating through all shared mailboxes and exporting results to CSV.
Prerequisites:
- Install the Exchange Online Management module: `Install-Module -1ame ExchangeOnlineManagement -Force -AllowClobber`
– Connect to Exchange Online with modern authentication: `Connect-ExchangeOnline -UserPrincipalName [email protected]`
Tenant-wide script (conceptual execution):
Download the full script from o365reports.com https://o365reports.com/shared-mailbox-permission-report-to-csv/ Basic execution (exports all shared mailboxes with all permission types) .\GetSharedMailboxPermissions.ps1 Export only Full Access permissions .\GetSharedMailboxPermissions.ps1 -FullAccess Export only Send As permissions .\GetSharedMailboxPermissions.ps1 -SendAs Export only Send on Behalf permissions .\GetSharedMailboxPermissions.ps1 -SendOnBehalf Export permissions for specific mailboxes listed in a text file .\GetSharedMailboxPermissions.ps1 -MBNamesFile C:\SharedMB.txt
Key features of the tenant-wide script:
- Exports output to a structured CSV file with attributes including Display Name, User Principal Name, Primary SMTP Address, Email Aliases, Access Type, and User with Access.
- Supports MFA-enabled accounts natively.
- Scheduler-friendly—credentials can be passed as parameters for automated Windows Task Scheduler integration.
- Allows granular filtering with switches like
-FullAccess,-SendAs, and-SendOnBehalf. - Ignores inherited permissions and system accounts by default, reducing noise.
Sample CSV output structure:
| DisplayName | UserPrincipalName | PrimarySmtpAddress | AccessType | UserWithAccess |
|-|-|-||-|
| Sales Shared | [email protected] | [email protected] | FullAccess | [email protected] |
| Sales Shared | [email protected] | [email protected] | SendAs | [email protected] |
- Linux and Cross-Platform Considerations for Exchange Online PowerShell
While Exchange Online PowerShell is traditionally associated with Windows, administrators on Linux or macOS can also execute these scripts using PowerShell Core (pwsh).
Installation on Linux (Ubuntu/Debian):
Update package list sudo apt-get update Install PowerShell Core sudo apt-get install -y wget apt-transport-https software-properties-common wget -q "https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/packages-microsoft-prod.deb" sudo dpkg -i packages-microsoft-prod.deb sudo apt-get update sudo apt-get install -y powershell Launch PowerShell pwsh
Connecting to Exchange Online from Linux/macOS:
Install the module (works cross-platform) Install-Module -1ame ExchangeOnlineManagement -Scope CurrentUser -Force Connect (device code authentication for non-Windows) Connect-ExchangeOnline -Device
Note: The `-Device` switch triggers device code authentication, which is essential for Linux/macOS environments where integrated Windows authentication is unavailable. All scripts discussed in this article run identically across platforms once the connection is established.
- Security Hardening: Auditing and Locking Down Shared Mailboxes
Auditing permissions is only half the battle. Security-conscious administrators must also implement controls to prevent excessive delegations.
Critical security risks:
- Compromised delegate accounts – If a delegate’s account is hacked, attackers gain access to the shared mailbox without needing separate credentials.
- Suspicious permission delegation – Adversaries may assign Full Access or Send As rights to compromised accounts to send phishing emails that appear legitimate, evading spam detection.
- Orphaned permissions – Deactivated or离职员工 accounts with lingering delegations create persistent access points.
Hardening checklist:
- Audit all shared mailboxes quarterly using the tenant-wide script and review the CSV output for:
– Users with Full Access who do not require it.
– Users with Send As (especially critical—treat this like shared account credentials).
– Delegations assigned to disabled or external accounts.
- Enable mailbox auditing to track non-owner access events:
Set-Mailbox -Identity "[email protected]" -AuditEnabled $true
Then run non-owner mailbox access reports from the Exchange Admin Center under Compliance Management → Auditing.
-
Block sign-in for shared mailboxes – Shared mailboxes should never have direct user sign-in enabled. Use this script to identify and block any that do:
Get-Mailbox -RecipientTypeDetails SharedMailbox | Set-Mailbox -Blocked $true
This ensures access is only possible through delegated permissions.
-
Implement the principle of least privilege – Regularly review and remove unnecessary Full Access permissions. Consider using security groups to manage delegations rather than individual assignments, simplifying revocation.
-
Monitor suspicious delegation events – Use Microsoft 365 audit logs to detect unusual delegation assignments, particularly from non-admin accounts.
6. Troubleshooting Common Permission Audit Issues
Issue 1: “User is not allowed to call Get-RecipientPermission”
This error typically indicates insufficient RBAC roles. The account running the script must have at least the Recipient Management or Exchange Administrator role. Assign the necessary role via the Exchange Admin Center or use a Global Admin account.
Issue 2: Inherited permissions cluttering the report
The single-mailbox script explicitly filters out inherited permissions (!$_.IsInherited). The tenant-wide script does this by default. If you’re writing custom scripts, always include this filter to avoid false positives from system accounts like “NT AUTHORITY\SELF”.
Issue 3: MFA blocking the script execution
Both scripts support MFA-enabled accounts. Use `Connect-ExchangeOnline` with the `-Device` switch for non-Windows environments or ensure you’re using the modern authentication flow.
Issue 4: Empty or missing Send On Behalf results
`GrantSendOnBehalfTo` returns `$null` if no delegates are configured. The script handles this gracefully, but if you expect delegates and see none, verify that Send on Behalf permissions were set via the Exchange Admin Center or the `Set-Mailbox` cmdlet.
7. Automating Regular Audits with Task Scheduler
For ongoing compliance, schedule the tenant-wide script to run monthly and email the CSV report to the security team.
Windows Task Scheduler setup:
1. Create a PowerShell script wrapper that:
- Imports the Exchange Online module.
- Connects using stored credentials (use `Get-Credential` or a secure string).
- Executes the permission report script.
- Sends the CSV via
Send-MailMessage.
2. Schedule the task:
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-File C:\Scripts\SharedMailboxAudit.ps1" $trigger = New-ScheduledTaskTrigger -Monthly -Days 1 -At 3am Register-ScheduledTask -TaskName "SharedMailboxAudit" -Action $action -Trigger $trigger -User "DOMAIN\ServiceAccount" -Password "SecurePassword"
Security note: Never store plaintext credentials in scripts. Use the Windows Credential Manager or Azure Key Vault for secure credential storage.
What Undercode Say:
- Key Takeaway 1: The consolidated PowerShell script transforms a fragmented, multi-cmdlet manual process into a single, repeatable audit command—reducing troubleshooting time from minutes to seconds and eliminating human error in permission correlation.
- Key Takeaway 2: Tenant-wide visibility is non-1egotiable for security. Organizations that rely on per-mailbox manual checks are almost certainly operating with unknown delegations, creating unnecessary risk exposure.
Analysis: The script’s elegance lies in its simplicity—three cmdlets, three filters, one unified output. However, the real value is in the shift it enables: from reactive, ad‑hoc permission checks to proactive, scheduled security audits. The inclusion of MFA support and scheduler compatibility means this isn’t just a developer’s tool; it’s an enterprise-grade control ready for integration into formal compliance programs. The most overlooked aspect is the exclusion of inherited permissions—without this, reports would be flooded with system entries, rendering them useless. By focusing on explicitly assigned delegations, the script surfaces exactly what security teams need to review: human‑assigned, potentially excessive access. Organizations should pair this script with mailbox auditing and sign-in blocking to close the loop on shared mailbox governance.
Prediction:
- +1 As regulatory frameworks (GDPR, HIPAA, SOX) intensify scrutiny on collaborative workspaces, automated permission auditing tools like this script will become mandatory controls rather than optional utilities, driving widespread adoption across regulated industries.
- +1 Microsoft will likely integrate native “shared mailbox permission summary” views into the Exchange Admin Center within the next 12–18 months, reducing reliance on third-party scripts—but PowerShell-based automation will remain the preferred method for advanced filtering, scheduling, and integration.
- -1 The rise of AI‑driven phishing attacks will make Send As permissions the most targeted delegation type; organizations that fail to audit and minimize Send As assignments will face elevated impersonation risks, potentially leading to high‑profile Business Email Compromise (BEC) incidents.
- -1 Without complementary controls like conditional access policies and anomaly detection, even perfect permission auditing cannot prevent compromised delegate accounts from abusing their legitimate access—meaning scripts alone are insufficient without a broader Zero Trust strategy.
▶️ Related Video (70% Match):
🎯Let’s Practice For Free:
🎓 Live Courses & Certifications:
Join Undercode Academy for Verified Certifications
🚀 Request a Custom Project:
Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
[email protected]
💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands
IT/Security Reporter URL:
Reported By: Hitendra Bhadoria – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


