How To Remove Email From All Mailboxes With Powershell

In this guide, I will walk through how you can utilize Powershell to remove a specific mail from multiple users’ mailboxes.

Why would this be useful?

Well, let’s say that multiple users start to report that they have received a phishing mail or mail containing malware. In this type of situation, it could be extremely useful to have a script that quickly removes the mail from all user’s mailboxes.

Fortunately, Powershell has provided the Powershell Module to handle Exchange and Content search actions through Powershell.

You could also perform these actions through the Office 365 Security & Compliance Portal, but Utilizing Powershell will make it a lot faster.

Prerequisites

Now before you get started you will need the Powershell Module ExchangeOnlineManagement. To download the module run the following command:

Install-Module ExchangeOnlineManagement -Scope CurrentUser

You should also be a member of the eDiscovery Manager role group in Security & Compliance Center.

To do this you will need to go to: https://protection.office.com/permissions

Find the eDiscovery Manager Role

Compliance Search

And enter yourself as an eDiscovery Manager

Once you have permissions set, you are ready to start creating content searches in your entire Tenant.

Connecting Powershell to Security & Compliance Center

To get started you will need to connect to the Security & Compliance Center through Powershell. To do this you can utilize the cmdlet Connect-IPPSSession. This cmdlet will accept users who have MFA enabled as well as not enabled.

To get connected run the following command:

Connect-IPPSSession -Credential (Get-Credential)

Searching for a specific e-mail

Creating a New Compliance Search

To search for a specific E-mail you will need to use the cmdlet New-ComplianceSearch. This cmdlet is used to create a Compliance search for some specific content in your Tenant.

Now you will need to set three different parameters:

Name: Name of the content search

ExchangeLocation: Which mailboxes to search in?

ContentMatchQuery: The specific search criteria

An example could be:

New-ComplianceSearch -Name "ContentSearch01" -ExchangeLocation all -ContentMatchQuery "subject:Hello Phishing mail"

This example will create a new search called: ContentSearch01. It will search in all mailboxes in the Tenant and search for all mail matching subjects with “Hello Phishing mail”.

To really specify your search criteria you could change the ExchangeLocation to a specific mailbox if you know that a mail has been sent to only this specific mailbox.

Or you can change the ContentMatchCriteria. To learn more about the ContentMatchCriteria’s you can read about it here on Microsoft Docs.

Searching for a specific sender

If you want to search for mail send with a specific sender you can run the following ContentMatchQuery:

$sender = sender@domain.com

-ContentMatchQuery "sender:$($sender)"

Searching for mails within a timespan

If you want to search for emails within a timespan you can run the following ContentMatchQuery

$StartTime = "05/23/2021"
$EndTime = "05/24/2021"

-ContentMatchQuery "sent>=$($StartTime) AND sent<=$($EndTime)"

Searching for a specific sender at a specific time with a specific subject:

You can combine the search criteria to specify your searches as much as possible with the following ContentMatchQuery:

$Sender = "sender@domain.com"
$StartTime = "05/23/2021"
$EndTime = "05/24/2021"
$Subject = "This was just a random mail"

-ContentMatchQuery "sent>=$($StartTime) AND sent<=$($EndTime) AND sender:$($Sender) AND subject:$($Subject)"

Starting the search

Now once you have created the Content Search, you will need to start it, to receive any results.

To start the content search run the following command:

Start-ComplianceSearch -Identity "ContentSearch01"

Start-ComplianceSearch -Identity “ContentSearch01”

Where the -Identity parameter is the name you set in New-ComplianceSearch

Getting the Search Status

Now once you start the Compliance search, it can take up to several minutes to finish depending on how big your tenant is, and what search criteria you have entered.

To get the status of the search you can run the following command:

Get-ComplianceSearch -Identity "ContentSearch01"

You will see by the output that the search is starting

Name            RunBy              JobEndTime Status
----            -----              ---------- ------
ContentSearch01 Administrator01               Starting

and once it has finished it the output will display:

Name            RunBy              JobEndTime Status
----            -----              ---------- ------
ContentSearch01 Administrator01               Completed

Reviewing the Search Results

Now once you have started the search and it has been completed you will need to review the search, to make sure that you are removing the correct e-mail. To do this you will need to run the following cmdlet:

New-ComplianceSearchAction -SearchName ContentSearch01 -Preview

Now again when creating the new Search action it can take a couple of minutes and you can monitor it by running the command:

Get-ComplianceSearchAction ContentSearch01_Preview

As you see, since you specified -Preview in the previous command the compliance search action will be named with _preivew at the end of the name.

Name                    SearchName      Action  RunBy              JobEndTime            Status
----                    ----------      ------  -----              ----------            ------
ContentSearch01_Preview ContentSearch01 Preview Administrator01    5/25/2021 10:53:49 AM Completed

To write the results of the preview in your Powershell console you can run the following command:

(Get-ComplianceSearchAction ContentSearch01_Preview | Select-Object -ExpandProperty Results).Split(";")

the output will look something similar to this:

If you want to see how many search action results you got, you can run the property NumBindings or run the following command:

(Get-ComplianceSearchAction ContentSearch01_Preview).Numbindings

Deleting the E-Mails from the Mailboxes

Now once you have completed the search and you have made sure the mails resulted in your preview is the actual mail you want to delete, you can proceed with purging the mail from all the mailboxes

Now to do this you can run the following cmdlet:

New-ComplianceSearchAction -SearchName ContentSearch01 -Purge -PurgeType SoftDelete

We set the parameter -Purge to remove the e-mails and then we set the parameter -PurgeType SoftDelete to make sure items are recoverable by users until the deleted item retention period expires.

You can also specify -PurgeType HardDelete to permanently remove the mails from the mailbox.

You will need to confirm the action on deleting the items:

Confirm
Are you sure you want to perform this action?
This operation will make message items meet the compliance search criteria "ContentSearch01" completely
inaccessible to users. There is no automatic method to undo the removal of these message items.
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [?] Help (default is "Y"): A

Again this action will take some minutes to complete. You can run the following command to check the progress:

Get-ComplianceSearchAction -Identity ContentSearch01_Purge

Notice that the Identity has now changed to _Purge at the end.

Once the process is done you should see the status “Completed” and the e-mails should now be removed from all the mailboxes.

Tips

If you are getting tired of waiting and manually run the command: Get-ComplianceSearchAction to see if the process is done, you can run the following snippet to an output of when the process is completed.

$identity = "ContentSearch01_Purge"

$action = Get-ComplianceSearchAction -Identity $identity
While ($action.Status -ne "Completed") {
	Write-Host "Working on it..." -ForegroundColor Yellow
	Start-Sleep -s 5
}
if ($action.Status -eq "Completed") {
	Write-Host "Search Completed!" -ForegroundColor Green
}

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *

This website uses cookies. By continuing to use this site, you accept our use of cookies.