rss logo

Microsoft 365 : How to search emails with PowerShell

Microsoft 365 Logo

We will see here how to search or trace Microsoft 365 emails with PowerShell.

Prerequisites

First thing to do is to install the Microsoft Exchange Online PowerShell Console which will allow us to connect to Microsoft 365 account via PowerShell. To do so you can use this beautiful article.

  • On your desktop you should see this icon appears :
Microsoft Exchange Online Powershell Module Icon

Connect to Microsoft 365

  • Use Connect-EXOPSSession to open the Microsoft 365 sign in window :
PS C:\> Connect-EXOPSSession -UserPrincipalName admin@std.rocks
  • Sign in with an admin account :
Microsoft 365, Sign in to your account window
  • Enter password :
Microsoft 365, Enter password window
  • Then you should be connected :
Microsoft 365, PowerShell Console

Commands to search emails

⚠️ It is not possible to search back more than 10 days.⚠️

Now everything is set and that we are connected to our Microsoft 365 account we can do some emails search.

  • Search for all messages which were sent from std.rocks domain over a period of 10 days :
PS C:\> Get-MessageTrace -StartDate $(get-date).AddDays(-10) -EndDate $(get-date) | Where-Object { $_.SenderAddress -match 'std.rocks' }
  • Search for all messages which were sent from std.rocks domain over a period of 10 days with detailed informations :
PS C:\> Get-MessageTrace -StartDate $(get-date).AddDays(-10) -EndDate $(get-date) | Select-Object Received, SenderAddress, RecipientAddress, Subject, Status, ToIP, FromIP, Size, MessageID, MessageTraceID | Where-Object { $_.SenderAddress -match 'std.rocks' }
  • Search with two conditions : all messages which were sent from std.rocks domain and to user@shebangthedolphins.net address over a period of 5 days with all informations :
PS C:\> Get-MessageTrace -StartDate $(get-date).AddDays(-5) -EndDate $(get-date) | Select-Object * | Where-Object { $_.SenderAddress -match 'std.rocks' -and $_.RecipientAddress -match 'user@shebangthedolphins.net' }
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Contact :

contact mail address