How to calculate incoming and outgoing emails for mailboxes on Exchange on Prem.

Updated 10 hours ago by admin

This guide shows you how to create a PowerShell script for Exchange Server On-Prem that totals the number of incoming and outgoing mailboxes over the last 31 days.

Explanation:

  1. Date Range: The script is set to analyze the last 31 days, but you can adjust the $StartDate and $EndDate variables as needed.
  2. Get-Mailbox: Retrieves all mailboxes in the organisation.
  3. Get-MessageTrackingLog: Searches the message tracking logs for each mailbox for incoming (RECEIVE) and outgoing (SEND) emails.
  4. Measure-Object: Counts the number of emails found in each search.
  5. Results Collection: Stores the results in a collection and exports them to a CSV file.

Steps to Run the Script:

  1. Copy the below PoweShell command text from the below section and save the script to a .ps1 file, e.g., ExchangeStats.ps1.

# Define the date range for the report

$StartDate = (Get-Date).AddDays(-31)

$EndDate = Get-Date

# Get all mailboxes

$mailboxes = Get-Mailbox -ResultSize Unlimited

# Initialize a collection to store results

$results = @()

foreach ($mailbox in $mailboxes) {    

$emailAddress = $mailbox.PrimarySmtpAddress.ToString()

# Get incoming emails    

$incomingEmails = Get-MessageTrackingLog -Start $StartDate -End $EndDate -Recipients $emailAddress -EventId RECEIVE | Measure-Object    

$incomingCount = $incomingEmails.Count

# Get outgoing emails    

$outgoingEmails = Get-MessageTrackingLog -Start $StartDate -End $EndDate -Sender $emailAddress -EventId SEND | Measure-Object    

$outgoingCount = $outgoingEmails.Count

# Store the result    

$results += [PSCustomObject]@{        

User             = $mailbox.DisplayName        

EmailAddress     = $emailAddress        

IncomingEmails   = $incomingCount        

OutgoingEmails   = $outgoingCount    

}

}

# Export the results to a CSV file

$results | Export-Csv -Path "C:\ExchangeStats.csv" -NoTypeInformation

Write-Output "Report generated successfully and saved to C:\ExchangeStats.csv"

  1. Open Exchange Management Shell and navigate to where you have saved the ExchangeStats.ps1script.
  1. Run the script: .\ExchangeStats.ps1.

This will generate a CSV file (C:\ExchangeStats.csv) with the number of incoming and outgoing emails for each mailbox.

  1. After the script has run successfully, it will display the below message.
  1. Here is an example of the output ExchangeStates.csv file.


How did we do?