Microsoft 365 : How to search emails with PowerShell
- Last updated: Jan 5, 2023
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 :

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 :

- Enter password :

- Then you should be connected :

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' }