In this post, I will show you how to, in the case of receiving a spam message that has been sent to all accounts within our tenant, search for that message and remove it from the mailboxes.
As I mentioned in the previous post, we first need to import the ExchangeOnline module and log in to PowerShell with an Office 365 administrative account.
1 2 3 |
Install-Module -Name ExchangeOnlineManagement Import-Module ExchangeOnlineManagement Connect-ExchangeOnline |
Now we can proceed with searching for emails. Before starting the search, we need to define the criteria by which we want to conduct the search.
1 2 3 4 5 |
$Search=New-ComplianceSearch -Name "Search Name" -ExchangeLocation All -ContentMatchQuery '(Received:9/8/2022..9/10/2023) AND (Subject:"Click here !!!")' $Search=New-ComplianceSearch -Name "Search Name" -ExchangeLocation mail@ourdomain.com -ContentMatchQuery '(Received:1/22/2021..2/23/2021) and (Subject:"Click here !!!") AND (from:"sender@domain.com")' $Search=New-ComplianceSearch -Name "Search Name" -ExchangeLocation All -ContentMatchQuery '(from:"sender@domain.com") ' |
I provided some examples above on how to search for emails. Once you have defined the search criteria, you can go ahead and initiate the search.
1 |
Start-ComplianceSearch -Identity $Search.Identity |
To check the status of the search, you can use the command:
1 |
Get-ComplianceSearch -Identity "Search Name" |
Once the search status is completed, you can view on which mailboxes the specific email was found.
1 |
Get-ComplianceSearch -Identity "Search Name" | Format-List * |
Now, you need to delete all the messages that were found. There are two deletion options – Soft and Hard. The first option deletes the message, but the user has the option to restore it from the Deleted Items, while the second option permanently deletes the message.
1 2 3 4 |
$searchaction = New-ComplianceSearchAction -SearchName "Search Name" -Purge -PurgeType SoftDelete $searchaction = New-ComplianceSearchAction -SearchName "Search Name" -Purge -PurgeType HardDelete Get-ComplianceSearchAction -identity $searchaction.Identity | Format-List * |