PowerShell script to search for and delete email messages

Brass Contributor

The script is based on Microsoft article https://docs.microsoft.com/en-us/microsoft-365/compliance/search-for-and-delete-messages-in-your-org... It tries to combine all steps at one place. It helps in a scenario wherein you want to delete e.g. a phishing email from user mailboxes. Please note that the script hard deletes the emails. If you want to soft delete the emails, you need to change -PurgeType parameter to SoftDelete. Please do share your feedback and suggestions.


##Please note that the script has been provided As Is. Test and use at your own risk.


Write-Host “The script finds and deletes unwanted such as a malicious email from user mailboxes.
Please make sure that you have at least ‘Compliance Search’ and ‘Search And Purge’ roles assigned in Security & Compliance Center.
A maximum of 10 items per mailbox can be removed at one time.” -ForegroundColor Yellow


##Importing modules if not already imported

$AlreadyImportedModules = Get-Module
$ModulesToCheck = @(“ExchangeOnlineManagement”)

ForEach($i in $ModulesToCheck){
If($AlreadyImportedModules.Name -notcontains $i){
Import-Module $i

##Connecting to Security & Compliance Center



##Finding the email

$Name = Read-Host “Please give a name to the search”
$ExchangeLocation = Read-Host “Please specify All to search all mailboxes. To specify particular mailboxes or distribution groups, specify their email address separated by comma”
$ExchangeLocation2 = $ExchangeLocation.Split(“,”).Trim()
$ContentMatchQuery = Read-Host “Please specify content search query in the format: (From:Email address removed) AND (Received:12/14/2021..12/15/2021) AND (Subject:”Phishing Email”)”
$Name2 = $Name + “_purge”

New-ComplianceSearch -Name $Name -ExchangeLocation $ExchangeLocation2 -ContentMatchQuery $ContentMatchQuery | Out-Null
Start-ComplianceSearch $Name | Out-Null

While((Get-ComplianceSearch $Name).Status -ne “Completed”){
Write-Host “Waiting for 2 minutes for the search to complete….” -ForegroundColor Yellow
Start-Sleep -Seconds 120

Get-ComplianceSearch $Name | FL Name,Status,ExchangeLocation,PublicFolderLocation,ContentMatchQuery,Items,Errors,NumFailedSources,@{Name=”Non0Results”;Expression={(Get-ComplianceSearch $Name).SuccessResults -Split “`n” -NotLike “item count: 0“}}

Read-Host “Please verify the search results above. Press Enter to hard delete the email or Ctrl+C to exit”


##Deleting the email

New-ComplianceSearchAction -SearchName $Name -Purge -PurgeType HardDelete -Confirm:$False | Out-Null

While((Get-ComplianceSearchAction $Name2).Status -ne “Completed”){
Write-Host “Waiting for 2 minutes for the delete action to complete….” -ForegroundColor Yellow
Start-Sleep -Seconds 120

Write-Host “The final delete action results are as following:” -ForegroundColor Yellow

Get-ComplianceSearchAction $Name2 | FL SearchName,Status,Errors,Results

0 Replies