Files
m365-administration/message-counter.ps1

41 lines
1.9 KiB
PowerShell

<#
.SYNOPSIS
Count the number of received emails in a Microsoft 365 mailbox during a specified time window.
.DESCRIPTION
This script queries Exchange Online via Microsoft Graph to return the total count of emails
received by a specific mailbox within a given date range. It searches all folders in the mailbox
(including Inbox, subfolders, Junk, and Deleted Items), ensuring that emails moved after delivery
are still included in the count. Drafts are excluded, and self-sent messages from the mailbox
owner are not counted as "received."
Date boundaries are applied using local time (Eastern Time in this example).
Adjust offsets (-05:00 / -04:00) for daylight savings or your region.
.PARAMETER $u
The target user's email address. Example: 'f@d.org'
.PARAMETER $start
The inclusive start of the time window in ISO 8601 format with time zone offset.
Example: '2025-01-01T00:00:00-05:00' for January 1st, 2025, 12:00 AM ET.
.PARAMETER $end
The exclusive end of the time window in ISO 8601 format with time zone offset.
Example: '2025-02-01T00:00:00-05:00' for February 1st, 2025, 12:00 AM ET.
.OUTPUTS
Returns a single integer representing the count of received messages.
.NOTES
Requirements:
- Microsoft.Graph PowerShell module
- Connect-MgGraph with Mail.Read delegated permission (if signed in as the user)
OR Mail.Read application permission (with admin consent) if run as a service.
Example to install module: Install-Module Microsoft.Graph
Example to connect: Connect-MgGraph -Scopes Mail.Read
(c) 2025 Robbie Ferguson. All rights reserved.
#>
$u='mailbox@domain.com';$start='2025-01-01T00:00:00-05:00';$end='2025-02-01T00:00:00-05:00';$c=0; Get-MgUserMessage -UserId $u -Filter "receivedDateTime ge $start and receivedDateTime lt $end and isDraft eq false and (from/emailAddress/address ne '$u')" -CountVariable c -PageSize 1 | Out-Null; $c