Getty Images

How to use PowerShell for Exchange Online monitoring

Many enterprises rely on Exchange Online for more than just email. Admins need to stay on top of this important service to pinpoint when problems occur to resolve them quickly.

Anytime there's a problem with email, it's a crisis. Being proactive and monitoring mail flow in Exchange Online help to get ahead of any problems to make sure this service is functioning properly.

Exchange Online is Microsoft's hosted email service that's included in Microsoft 365 and used by businesses around the world. Other critical work functions tie into this service, such as calendaring and contact management, and it integrates with other Microsoft 365 applications. If users experience problems with Exchange Online, then those troubles may be a sign of bigger issues. PowerShell is one management tool that excels in Microsoft-based environments and can be used to monitor Exchange Online. With PowerShell, IT professionals can access detailed information to ensure the organization's communication systems operate efficiently and securely.

Why use PowerShell with Microsoft cloud services?

PowerShell is a command-line shell and scripting language IT professionals use to automate administrative tasks across multiple Microsoft products and services. With Exchange Online, PowerShell is particularly helpful with user management, mailbox configuration and email flow monitoring.

Automation reduces the time spent on repetitive tasks, performs bulk tasks quicker and minimizes the chance of errors. Additionally, automation eases configuration work in Exchange Online to comply with industry standards and regulations, such as GDPR and HIPAA.

What are the benefits of using PowerShell with Exchange Online?

An advantage of using PowerShell to manage Exchange Online is it provides administrative capabilities not available through the admin portal interface. The following are two specific areas that make it optimal to use PowerShell with Exchange Online.

Enhanced administrative control and automation

Exchange admin center (EAC) presents a user-friendly interface for basic tasks, while PowerShell executes complex and bulk operations with just a few lines of code. For repetitive tasks, such as mailbox creation, configuration changes and report generation, PowerShell is ideal. It saves valuable time and reduces the chance of errors, making it ideal for large organizations where manually managing hundreds or thousands of mailboxes is impractical.

You can schedule PowerShell scripts to run at specific times, such as outside business hours, to perform regular maintenance tasks. This minimizes the potential impact on the organization's operations. In addition, scheduling helps maintain compliance standards, which is essential for organizations that must adhere to regulatory requirements.

Advanced features and customization

PowerShell offers access to an expanded set of functions and settings in Exchange Online that are not available through EAC. For instance, PowerShell is more effective at handling detailed mailbox reports, complex query-based distribution groups and advanced message tracking. By scripting these tasks, administrators have better control over the Exchange environment with the ability to fine-tune settings and configurations to the organization's needs.

PowerShell's extensibility makes it possible to integrate with other Microsoft 365 services and third-party tools for a more comprehensive approach to managing the IT infrastructure. Through this integration, admins have a way to automate tasks across multiple platforms, streamline workflows and use a more unified management experience.

How to connect PowerShell to Exchange Online

Using PowerShell with Exchange Online requires using the ExchangeOnlineManagement module from Microsoft. It is also referred to as the Exchange Online PowerShell V3 module or the EXO V3 module.

This version of the module is relatively new and gives admins a modern and reliable way to connect to Exchange Online. The module also connects to other PowerShell areas that connect to Exchange Online in Microsoft 365, such as Security & Compliance and Exchange Online Protection.

Install the module directly from PowerShell Gallery using the following command:

Install-Module -Name ExchangeOnlineManagement

When complete, administrators can initiate a connection via the Connect-ExchangeOnline command, which prompts for the administrator's Microsoft 365 credentials and establishes a secure session with Exchange Online.

Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline​

What are the benefits of the ExchangeOnlineManagement module?

The ExchangeOnlineManagement module brings several advantages. It supports modern authentication methods, including multifactor authentication (MFA), for added security to the connection process.

Additionally, Microsoft updates the module regularly to include new cmdlets and improve functionality to give admins the latest tools and features to manage the Exchange Online environment.

The simplicity of this connection method reduces setup time and complexity to give administrators time to focus on more strategic tasks. The module integrates seamlessly with other PowerShell cmdlets and scripts for a cohesive and efficient management experience.

How to monitor Exchange Online mail flow with PowerShell

PowerShell enables administrators to track and analyze the flow of email to identify issues, such as delays and nondelivery, and understand overall email traffic patterns. PowerShell can retrieve granular details related to mail flow to aid troubleshooting, auditing and compliance.

For example, the Get-MessageTrace cmdlet traces messages as they pass through the Exchange Online environment to gather detailed information about the sender, recipient, subject and status of each email -- all crucial elements to diagnose issues related to mail delivery.

How to trace email in Exchange Online with PowerShell

Using PowerShell to monitor Exchange Online, you can track both sent and received email to build an understanding of email activities within an organization. It's also useful to perform audits to ensure compliance with internal policies or even investigate security incidents.

The Get-MessageTrace PowerShell cmdlet offers detailed insights into these activities. For example, you can track all email a user receives during a specific period. The Get-MessageTrace command can fetch the email traffic directed to the user and provide critical information, such as the origin of the email, timestamps and subjects, to produce a comprehensive analysis of incoming email patterns.

The following PowerShell command tracks received email:

Get-MessageTrace `
    -SenderAddress "[email protected]" `
    -StartDate "2023-11-25" `
    -EndDate "2023-11-30" | `
        Select-Object Received, SenderAddress, `
            RecipientAddress, Subject, Status
​
Get-MessageTrace email report
Use the Get-MessageTrace cmdlet to generate a detailed report about email sent to your organization.

The PowerShell code returns details of all email sent by [email protected] between Nov. 25, 2023, and Nov. 30, 2023. The output includes when the user received the email, the address of the sender, the recipient's address, the email's subject line and the status, which indicates if the email was successfully delivered or encountered issues.

PowerShell provides an overview of overall email traffic patterns to identify trends, peak periods of email activity and potential bottlenecks in mail flow. For instance, PowerShell can produce an Exchange Online report by compiling data on sent and received email over extended periods to highlight the most active users, times when email traffic is highest and common subjects or recipients in sent email. Analyzing these findings is helpful to find areas to adjust to boost efficiency and reliability of the organization's email system.

The following command gathers a comprehensive set of data between two dates for both sent and received email:

Get-MessageTrace `
    -StartDate "2023-11-25" `
    -EndDate "2023-11-30" | `
         Select-Object Date, SenderAddress, `
            RecipientAddress, Subject, Status
email log
The Get-MessageTrace command can generate a log of all email sent and received in the organization between dates.

This following PowerShell command filters email with the keyword "ATP submission" in the subject line over the past 10 days:

Get-MessageTrace `
    -StartDate (Get-Date).AddDays(-10) `
    -EndDate (Get-Date) | `
        Where-Object {$_.Subject -like "*ATP submission*"} | `
            Select-Object Date, SenderAddress, `
                RecipientAddress, Subject, Status

To track email sent from your organization to a specific external domain, use the following command:

Get-MessageTrace `
    -StartDate "2023-11-25" `
    -EndDate "2023-11-30" | `
        Where-Object {$_.RecipientAddress -like "*@nasmis.com"}

To identify email that failed to deliver, you can filter by status:

Get-MessageTrace `
    -StartDate "2023-11-25" `
    -EndDate "2023-11-30" | `
        Where-Object {$_.Status -eq "Failed"}

The Get-MessageTrace cmdlet produces a detailed trace of email exchanged in a specific conversation thread. For example, the following code lists all email with the subject "Project Update" sent between specific dates in November 2023 with detailed information about each message:

Get-MessageTrace `
    -StartDate "2023-11-25" `
    -EndDate "2023-11-30" | `
        Where-Object {$_.Subject -eq "Project Update"} | `
            Select-Object Date, SenderAddress, `
                RecipientAddress, Subject, Status

How to monitor mailboxes in Exchange Online with PowerShell

It's important to stay on top of mailbox monitoring in Exchange Online for optimal performance and to ensure compliance with storage policies. If a user goes over their mailbox quota, then incoming email might not arrive. The Get-MailboxStatistics cmdlet in PowerShell is an effective tool to gather information about Exchange Online mailboxes.

The following PowerShell code finds the top five largest mailboxes in your organization and outputs the size, item count and last accessed time:

Get-Mailbox `
    -ResultSize Unlimited | `
        Get-MailboxStatistics | Sort TotalItemSize -Descending | `
            Select -First 5 DisplayName, TotalItemSize, `
                ItemCount, LastLogonTime
Exchange Online mailbox details
The Get-Mailbox command gives specifics about mailboxes in Exchange Online, including the size.

What is the difference between the Get-MailBox and Get-EXOMailBox cmdlets?

In addition to the Get-MailBox cmdlet, you can also use the Get-EXOMailBox cmdlet. Both help manage mailboxes in Exchange Online, but they belong to different PowerShell modules and have some distinct characteristics.

The Get-Mailbox cmdlet is integral to the older Exchange Online PowerShell module, commonly known as Exchange V1, which is included with PowerShell. This cmdlet retrieves a wide array of mailbox properties and information, such as comprehensive details about different mailbox types, including user, shared and resource mailboxes and their features and configurations.

Get-Mailbox is well integrated with other cmdlets in the V1 module, making it a familiar and reliable choice for those with experience managing on-premises Exchange Server.

On the other hand, Get-EXOMailbox belongs to the ExchangeOnlineManagement PowerShell module, or V3 module, which represents a more modern and efficient approach that is especially beneficial for large-scale operations. While it serves a similar purpose as Get-Mailbox, Get-EXOMailbox uses REST-based APIs for faster performance, particularly when working with a high number of mailboxes or executing complex scripting scenarios in Exchange Online. Get-EXOMailbox has faster data retrieval, reduced throttling and support for modern authentication methods, such as MFA. Get-EXOMailbox is more suitable for performance-intensive environments and should extend the life span of administrative scripts.

For example, the Get-EXOMailBox and Get-EXOMailboxStatistics commands in the following PowerShell script find mailboxes larger than 5 MB:

Get-EXOMailbox -ResultSize Unlimited | `
    Get-EXOMailboxStatistics | `
        Where-Object {[int64]($PSItem.TotalItemSize.Value -replace '.+\(|bytes\)') -gt "5MB"} | `
        Sort-Object TotalItemSize -Descending | `
            Select-Object DisplayName, ItemCount, TotalItemSize, LastLogonTime
mailbox storage sizes
The Get-EXOMailbox cmdlet identifies potential problems with user mailbox storage.

The following command uses the Get-MailBox and Get-MailboxStatistics commands to detect unauthorized mailbox access:

Get-Mailbox -ResultSize Unlimited | ForEach-Object {
    $mailboxStats = Get-MailboxStatistics -Identity $_.Identity
    [PSCustomObject]@{
        Mailbox = $_.DisplayName
        LastLogonTime = $mailboxStats.LastLogonTime
    }
} | Format-Table -AutoSize

How to search the unified audit log with PowerShell

The Search-UnifiedAuditLog cmdlet performs auditing tasks in Exchange Online, including searching the audit logs for user and admin actions on mailboxes.

The following PowerShell example outputs specific activities on mailboxes from the last 90 days:

$startDate = (Get-Date).AddDays(-90)
$endDate = Get-Date
$recordTypes = 1
$auditLogs = Search-UnifiedAuditLog `
    -StartDate $startDate `
    -EndDate $endDate `
    -RecordType $recordTypes
 
$auditLogs | Select-Object CreationDate, Operations, AuditData | `
Format-Table -AutoSize
mailbox auditing
Get more granular information about actions on mailboxes with the Search-UnifiedAuditLog cmdlet.

How to troubleshoot Exchange Online issues

Exchange Online issues that interrupt email services need to be remedied quickly. Common problems you might encounter include mail delivery failures, connectivity issues and performance problems. PowerShell can diagnose and address these issues.

How to identify email nondelivery reports

There are several reasons why mail delivery failures occur in Exchange Online, such as incorrect email addresses, server issues or policy restrictions. To find nondelivery reports for email sent by any user, you can use the Get-MessageTrace cmdlet:

Get-MessageTrace `
    -StartDate "2023-11-25" -EndDate "2023-11-30" | `
        Where-Object {$_.Status -eq "Failed"}

This example lists all failed email attempts between the start and end dates to try to identify patterns or recurring issues.

For a deeper analysis, you can use the Get-MessageTraceDetail cmdlet to view details of a specific message trace. This command provides in-depth information about the failure, which is crucial for troubleshooting:

Get-MessageTraceDetail `
    -MessageTraceId cdd71640-b8b1-4e9e-6463-08dbf12da9cc `
    -RecipientAddress [email protected]

How to uncover performance problems in Exchange Online

Microsoft manages much of the underlying infrastructure to Exchange Online to make it a challenge to discover the root of performance problems. However, PowerShell can gather enough information to assist with the troubleshooting process.

Signs of performance issues include unusually high activity levels in a mailbox and slow mail delivery. This PowerShell code finds any email delayed in the past 24 hours:

Get-MessageTrace `
    -StartDate (Get-Date).AddDays(-1) `
    -EndDate (Get-Date) | `
        Where-Object {$_.Status -eq "Delayed"}

At times, a performance problem happens due to unusual or unauthorized activities. With help from the Search-UnifiedAuditLog cmdlet, the following PowerShell script checks for unusual activity on mailboxes between the specified dates:

$startDate = "2023-11-25"
$endDate = "2023-11-30"
$operations = "Move", "MoveToDeletedItems", "SoftDelete", "HardDelete"
$auditLogs = Search-UnifiedAuditLog `
    -StartDate $startDate `
    -EndDate $endDate `
    -Operations $operations `
    -RecordType ExchangeItem
 
$auditLogs | Select-Object CreationDate, UserIds, Operations, AuditData | `
    Format-Table -AutoSize

Since Exchange Online is a managed service, Microsoft's support team might need to step in and address any issues you uncover.

Liam Cleary is founder and owner of SharePlicity, a technology consulting company that helps organizations with internal and external collaboration, document and records management, business process automation, automation tool deployment, and security controls and protection. Cleary's areas of expertise include security on the Microsoft 365 and Azure platforms, PowerShell automation and IT administration. Cleary is a Microsoft MVP and a Microsoft Certified Trainer.

Dig Deeper on Microsoft messaging and collaboration