/
/

How to Detect and Disable Inactive Mailboxes Shared Across Client Tenants

by Mauro Mendoza, IT Technical Writer
How to Detect and Disable Inactive Mailboxes Shared Across Client Tenants blog banner image

Instant Summary

This NinjaOne blog post offers a comprehensive basic CMD commands list and deep dive into Windows commands with over 70 essential cmd commands for both beginners and advanced users. It explains practical command prompt commands for file management, directory navigation, network troubleshooting, disk operations, and automation with real examples to improve productivity. Whether you’re learning foundational cmd commands or mastering advanced Windows CLI tools, this guide helps you use the Command Prompt more effectively.

Microsoft 365 shared mailboxes are invaluable for team collaboration, but neglected ones become a silent drain on resources and a security liability. Automating the process to get inactive mailbox reports is crucial for maintaining a secure, compliant, and cost-efficient environment.

In this guide, you will learn how to identify these dormant accounts, generate clear audit reports, and apply remediation actions using PowerShell across your client tenants.

Method for identifying and managing inactive mailboxes via PowerShell

Keeping your Microsoft 365 tenants clean of unused shared mailboxes strengthens security, improves performance, and simplifies audits.

📌 Use case: Perform this cleanup during regular maintenance, client onboarding/offboarding, or quarterly reviews (QBRs) to ensure compliance and efficient resource use.

📌 Prerequisites: Before proceeding, ensure you have:

  • A Microsoft 365 Global Admin or Exchange Admin role.
  • The Exchange Online PowerShell module is installed.
  • PowerShell 5.1 or later versions.
  • (Optional) An RMM tool like NinjaOne for running scripts at scale across multiple tenants.
  • (Optional) Registry tagging for hybrid environment tracking.

We recommend checking ⚠️ Things to look out for before proceeding.

Step 1: Connect to Exchange Online via PowerShell

To manage mailboxes across client tenants, you first need a secure connection to Microsoft 365.

  1. Open PowerShell (Admin) or Windows Terminal (Admin).
  2. Install the required module.
    • Run the following command to install the ExchangeOnlineManagement module. Confirm any prompts that appear:

Install-Module -Name ExchangeOnlineManagement -Force -AllowClobber

  1. Establish the connection.
    • Run the command below, replacing [email protected] with your admin account. A modern authentication window will open for you to sign in.

Connect-ExchangeOnline -UserPrincipalName [email protected]

Once connected, you can list, audit, and manage mailboxes across your tenants using the steps below.

Step 2: Identify all shared mailboxes and the last logon timestamp

To find inactive mailboxes, you first need to gather a list of all shared mailboxes and check their last access date.

After connecting to Exchange Online, run the following PowerShell commands.

  1. Get all shared mailboxes in the tenant:

$sharedMailboxes = Get-Mailbox -RecipientTypeDetails SharedMailbox -ResultSize Unlimited

  1. Check the last logon time for each mailbox:

$sharedMailboxes = Get-Mailbox -RecipientTypeDetails SharedMailbox -ResultSize Unlimited
$mailboxReport = foreach ($mb in $sharedMailboxes) {
$auditLog = Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-90) -EndDate (Get-Date) -Operations "MailItemsAccessed" -UserIds $mb.PrimarySmtpAddress
[PSCustomObject]@{
DisplayName = $mb.DisplayName
PrimarySMTP = $mb.PrimarySmtpAddress
LastActivity = if ($auditLog) { ($auditLog | Sort-Object CreationDate -Descending | Select-Object -First 1).CreationDate } else { "No Activity Found" }
}
}
$mailboxReport | Format-Table -AutoSize

Once completed, you will have a clear report showing which shared mailboxes are active and which are dormant. This report becomes the basis for your next actions: either disabling the mailbox or converting it to an inactive state for compliance purposes.

Step 3: Filter and export dormant mailboxes

Now that you have collected activity signals, you can begin identifying which mailboxes may have been inactive beyond your defined threshold.

Using the list of mailboxes gathered in Step 2, the following PowerShell script filters them based on the selected activity indicator and a defined threshold (e.g., 90 days), then exports the results to a CSV file for review.

  1. Define your inactivity threshold (e.g., 90 days):

$cutoffDate = (Get-Date).AddDays(-90)

  1. Filter the list of shared mailboxes to find dormant ones:

$cutoffDate = (Get-Date).AddDays(-90)

$dormantMailboxes = foreach ($mb in $sharedMailboxes) {
$auditLog = Search-UnifiedAuditLog -StartDate $cutoffDate -EndDate (Get-Date) -Operations "MailItemsAccessed" -UserIds $mb.PrimarySmtpAddress
if (-not $auditLog) {
[PSCustomObject]@{
DisplayName = $mb.DisplayName
PrimarySMTP = $mb.PrimarySmtpAddress
LastActivity = "No Activity Found"
}
}
}

  1. Export the results to a CSV file:

$dormantMailboxes | Export-Csv -Path "C:\Reports\InactiveSharedMailboxes.csv" -NoTypeInformation

After running this script, you will have a CSV file listing shared mailboxes with no activity found based on the selected audit signal. This report can be used as a review list for follow-up actions such as access review, archival evaluation, or other lifecycle decisions, depending on your organization’s requirements.

Step 4: Manage Shared Mailboxes with No Activity Found

Once you have identified shared mailboxes with no recent activity signals from the previous step, review and validate them before taking any action. Based on your organization’s compliance and lifecycle requirements, select the appropriate management action for each mailbox included in your report.

  • Option 1: Block sign-in for the associated account.
    • This action blocks interactive sign-in for the associated account, helping reduce unauthorized access paths while preserving mailbox data and configuration:

Set-Mailbox -Identity "SharedMailboxName" -AccountDisabled $true

  • Option 2: Remove delegated permissions (recommended before disabling)
    • Remove full access permissions for a specific user:

Remove-MailboxPermission -Identity "SharedMailboxName" -User [email protected] -AccessRights FullAccess -Confirm:$false

    • Remove Send As permissions for a specific user:

Remove-RecipientPermission -Identity "SharedMailboxName" -Trustee [email protected] -AccessRights SendAs -Confirm:$false

  • Option 3: Convert to a regular user mailbox (for archival purposes)
    • Run this script:

Set-Mailbox -Identity "SharedMailboxName" -Type Regular

  • Option 4: Tag for retention tracking
    • Use a custom attribute to label mailboxes for identification, reporting, or follow-up actions within your management processes:

Set-Mailbox -Identity "SharedMailboxName" -CustomAttribute1 "Inactive_90Days"

After completing this procedure, the targeted mailboxes can have delegated access removed, be converted to a different mailbox type, or be labeled for internal tracking based on your management needs. These actions help improve administrative visibility and support follow-up management activities.

The changes take effect immediately; however, it is recommended to validate the results by reviewing mailbox properties and permissions (e.g., using Get-Mailbox, Get-MailboxPermission, or Get-RecipientPermission) for each processed mailbox.

Optional step: Store metadata in the Registry or log file

For hybrid environments or local tracking, you can record your audit results directly in the Windows Registry.

This optional step creates a permanent record of your scan on your management machine, which is useful for tracking trends or integrating with on-premises systems:

  1. Create Registry key path (run as Administrator):

New-Item -Path "HKLM:\SOFTWARE\YourOrg\MailboxAudit" -Force

  1. Record timestamp and count of dormant mailboxes:

Set-ItemProperty -Path "HKLM:\SOFTWARE\YourOrg\MailboxAudit" -Name "LastDormantScan" -Value (Get-Date).ToString("u")
Set-ItemProperty -Path "HKLM:\SOFTWARE\YourOrg\MailboxAudit" -Name "DormantMailboxesCount" -Value $dormantMailboxes.Count

  1. Verify via Command Prompt (Admin):

reg query HKLM\SOFTWARE\YourOrg\MailboxAudit

After implementation, your system will maintain a verifiable history of mailbox audit activities that can be referenced for compliance reports or integrated with monitoring tools. The registry entries will persist until manually modified or removed, providing a long-term record of your tenant hygiene efforts.

⚠️ Things to look out for

This section highlights potential challenges to keep in mind while following this guide.

RisksPotential ConsequencesReversals
1. Incorrectly Identifying Inactivity ($null LastLogonTime)A mailbox with no logon time ($null) may be a new mailbox never used, or one accessed only via protocols that don’t update this statistic. Mistaking it for dormant could disrupt a critical active mailbox.Cross-reference with other data like mail flow logs (MessageTrace) or the Unified Audit Log for MailItemsAccessed events before taking action.
2. Insufficient Administrator PermissionsRunning Get-MailboxStatistics or Set-Mailbox without the Exchange Administrator role will result in errors, script failures, and an incomplete report.Ensure your account has the appropriate roles assigned (e.g., Exchange Administrator) and sufficient permissions within Exchange Online (RBAC) before running PowerShell commands.
3. Accidental Data Loss or Service InterruptionDisabling a mailbox that is still in use or converting a shared mailbox to a regular user mailbox will immediately break team access and disrupt business operations.Restore access immediately by reversing the command:

Set-Mailbox -Identity "MailboxName" -AccountDisabled $false

Or reconvert it:

Set-Mailbox -Identity "MailboxName" -Type Shared

4. Script Timeouts in Large TenantsRunning statistics queries against thousands of mailboxes can trigger Exchange Online throttling policies, causing the script to fail or return incomplete data.Use paging with the -ResultSize Unlimited parameter and introduce delays (StartSleep -Seconds 2) between batches of requests to avoid throttling.
5. Registry Corruption (Optional Step)Editing the Windows Registry without a backup can corrupt the system configuration, leading to application errors or system instability.Always export a backup of the registry key before making changes:

reg export HKLM\SOFTWARE\YourOrg C:\backup\MailboxAuditBackup.reg

If an error occurs, import the backup to restore the previous state.

6. False Positives in Audit ReportsRelying solely on the LastLogonTime might miss mailboxes that are used for sending automated alerts or receive only occasional, crucial emails, leading to incorrect classification.Implement a multi-factor review process. Check for recently sent items, inbox rules, or forwarding addresses before finalizing the dormant mailbox list.

Key considerations for secure shared mailbox management

Successfully managing inactive mailboxes requires careful planning beyond just running scripts.

Enable mailbox audit logging

Before taking any action, ensure mailbox audit logging is enabled for your shared mailboxes.

This provides detailed records of who accessed the mailbox and when, creating an essential trail for future checks if a shared mailbox is active and for compliance auditing. This historical data is invaluable if you need to verify usage patterns after the fact.

Align with Retention Policies and Legal Holds

Always cross-reference your list of dormant mailboxes with your organization’s Microsoft 365 retention policies and legal holds.

A mailbox under litigation hold or an active retention policy cannot be permanently deleted and must be preserved in its entirety. Disabling access is acceptable, but data must be retained according to your compliance requirements.

Verify Shared Mailbox Licensing

While shared mailboxes under 50GB typically don’t require a license, confirm this before conversion or deletion. Some integrated applications or historical configurations might have assigned a license.

Additionally, review any security or service configurations applied to shared mailboxes, as certain features or integrations may introduce licensing considerations depending on how the mailbox is used.

Secure Scripting Across Multiple Tenants

When automating this process across client tenants, never store admin credentials in plain text within scripts. Utilize secure methods like Azure Key Vault or certificate-based authentication (app registrations) to enable controlled and non-interactive access.

These practices reduce the risk of credential exposure and support secure, scalable automation across environments.

How automation tools like NinjaOne support the process

An RMM platform can automate the execution of mailbox management tasks, enabling more consistent workflows for MSPs.

FeatureHow it helps
Centralized Script DeploymentRun the necessary PowerShell scripts to get inactive mailbox data across all clients from a single dashboard, eliminating manual per-tenant connections.
Automated Audit & ReportingUse the RMM platform to collect script output and generate reports across managed endpoints, which can be used to review mailbox activity data.
Proactive Alerting Configure triggers to create tickets or alerts if dormant mailboxes exceed a set threshold, enabling proactive remediation before an audit.
Workflow IntegrationEmbed these automated checks into standardized procedures for client onboarding (QBRs), ensuring consistent and billable tenant hygiene.

Learning how to identify inactive mailboxes to improve operational visibility

Mastering how to get inactive mailbox reports is essential for eliminating security risks and reducing administrative clutter in your Microsoft 365 tenants. This guide provided a clear path to identify dormant accounts with PowerShell, disable or tag them for compliance, and export reports for client reviews.

By automating this process, you can transform a tedious manual task into a scalable, proactive strategy that enhances tenant hygiene and security across your entire client base.

You might also like

Ready to simplify the hardest parts of IT?