Scenario: You need a scriptlet that will search for all messages in Exchange Online looking for a specific sending email address pattern. Specifically I am looking for any email sent by any impersonating email address that looks like this: Steve.Contoso.com@gmail.com. I want to filter on the “.com@” pattern.
Scriptlet: Edit the “Configure these Variables” section and copy and paste the remainder of the script below.
#Look for the text pattern “.com@” as the sending addresses
#Configure these Variables
$filter = “.com@”
$start = “1/11/2021 00:00”
$end = “1/11/2021 23:59”
$pageSize = 1000
$P = 1
$messages = @()
$report = @()
$totalRecipients = 0
#End_Configure these Variables#######
#The Loop – no need to edit anything below
#Create Starting Loop Variables
$Loop_start = get-date($start) -format “MM/dd/yyyy HH:00:00”
$Loop_end = get-date($end) -format “MM/dd/yyyy HH:00:00”
$1Hour_end = get-date($Loop_start)
$1Hour_end = $1Hour_end.AddHours(1)
$1Hour_end = get-date($1Hour_end) -format “MM/dd/yyyy HH:00:00”
#Loop through All Messages
do
{
Do{
Write-Host “Message Trace $Loop_Start : $1Hour_end – Page $P…”
$temp_Messages = Get-MessageTrace -startdate $loop_Start -enddate $1Hour_End -PageSize $pagesize -Page $P
$filtered_messages = $temp_messages | Where SenderAddress -like “$filter“
$P++
$Messages += $filtered_Messages
}until ($temp_Messages -eq $null)
#recreate new variables
$P = 1
$Loop_Start = $1hour_end
$1Hour_end = get-date($Loop_start)
$1Hour_end = $1Hour_end.AddHours(1)
$1Hour_end = get-date($1Hour_end) -format “MM/dd/yyyy HH:00:00”
}While((get-date($Loop_start)) -lt (Get-date($Loop_End)))
#View the Results
$Messages