PowershellWindows

Search-Mailbox: How to Find and Delete Email from Exchange User Mailboxes

By May 1, 2019October 30th, 2019No Comments

An Exchange server allows an administrator to search user mailboxes in the databases and delete certain emails (or other items) from the mailboxes. For example, a user has accidentally sent private data to other users in a company and couldn’t recall this email in Outlook in time. The information security department requires that you as the Exchange administrator delete this email from all user’s mailboxes in your Exchange organization. In this article we’ll show how to use PowerShell to search the Exchange user mailboxes (by different criteria) and delete certain emails from the mailbox of the specific user or all Exchange users. The techniques described below are applicable to Exchange 2016, 2013 and 2010.

How to Assign Permissions to Search through Exchange Mailboxes?

The following roles must be assigned to the administrator account who searches for and deletes mailbox items:

  • Mailbox Import Export
  • Mailbox Search

You can assign the roles using EAC or these PowerShell commands:

New-ManagementRoleAssignment -User corey -Role "Mailbox Import Export"
New-ManagementRoleAssignment -User corey -Role "Mailbox Search”

exchange roles: Mailbox Import Export, Mailbox Search

After the roles have been assigned, restart the Exchange Management Shell console.

Using the Search-Mailbox to Search & Delete Messages from Exchange User Mailboxes

You can also search for email items in the user mailboxes using the Exchange Control Panel or Exchange Admin Center, but this search method is quite slow and doesn’t allow you to remove email messages. It is much easier to search using PowerShell.

To search email items in user mailboxes, you can use the Search-Mailbox cmdlet that allows you to search items that meet certain criteria in all or specific mailboxes, copy the found items to another mailbox or remove them.

First of all, let’s consider, how to find something using the Search-Mailbox cmdlet.
To search a mailbox for items with a specific subject, run this command:
Search-Mailbox -Identity corey -SearchQuery 'Subject:"Annual Report"'
To search all mailboxes in the Exchange organization, use the following command:
Get-Mailbox -ResultSize unlimited | Search-Mailbox -SearchQuery 'Subject:"Annual Report"'

To copy the search results to a certain mailbox and folder, use the TargetMailbox or TargetFolder parameters. Thus, after the search is completed, you can view the found items manually using Outlook or OWA. Suppose you need to search for email messages in list of users (given in users.txt) and copy the found items to the folder in the specific mailbox. To do it, run this command:

get-content users.txt | Get-Mailbox -ResultSize unlimited | Search-Mailbox -SearchQuery 'Subject:"Annual Report"' -TargetMailbox sec_dept -TargetFolder "ExchSearchResult”

The –LogOnly parameter means that search results must only be estimated without copying items to a target mailbox or deleting the messages. If this argument is used, a report containing the search results will be sent to the specified target mailbox. A report is an archived CSV file that lists mailboxes meeting the search criteria.

You can estimate the search results using the –EstimateResultOnly parameter. Please, note that when using this argument you don’t need to specify a target mailbox or folder.

To remove the found email items, use the –DeleteContent parameter, and to skip confirmation requests to delete items, add the –Force parameter.

Let’s delete all email messages from the sender [email protected] in all mailboxes on the specific Exchange server:

Get-Mailbox –Server berl-ex1 –ResultSize unlimited | Search-Mailbox -SearchQuery 'from:"[email protected]"' –DeleteContent –ForcePrior to deleting messages from mailboxes using the -DeleteContent parameter, we strongly recommend to look through the found emails using the -EstimateResultOnly or –LogOnly arguments.

Get-Mailbox: DeleteContent parameter

To search only among deleted elements, add the –SearchDumpsterOnly parameter (to exclude search among the deleted items, add the -SearchDumpster:$false argument). If you need to exclude from the search result an archive mailbox, use the –DoNotIncludeArchive parameter.

Search-Mailbox: Search Query Examples

Let’s consider the examples of search queries to find email messages using the SearchQuery parameter. The SearchQuery key processes queries in the KQL (Keyword Query Language) — https://docs.microsoft.com/ru-ru/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference.

To remove all email messages containing the keyword “Secret” in the subject of the emails from all users not from your domain:

Search-Mailbox -Identity corey -SearchQuery 'Subject:"Secret" and from<>”zamarax.com”' -DeleteContent

Find and delete all emails with the attachments exceeding 20 MB:

Search-Mailbox -Identity corey -SearchQuery 'hasattachment:true AND Size >20971520' –DeleteContentTip. The size of the email items is specified in bytes, and the size of the whole message is counted, not only the attachments. You can also specify the size in megabytes, and in this case the following syntax is used: -SearchQuery {Size -gt 30MB}.

You can simultaneously search for the text in the subject and body of the email. For example, let’s find and delete all messages containing “New Year” in the subject or “brandy” in the email body.

Search-Mailbox corey -SearchQuery {Subject:"RE:New Year" OR body:"brandy"} -DeleteContent -Force

You can search the mailboxes for certain elements using Kind argument, for example:

Meetings: -SearchQuery "Kind:meetings"
Contacts: -SearchQuery "Kind:contacts"

Or other Outlook elements:

  • Email
  • Meetings
  • Tasks
  • Notes
  • Docs
  • Journals
  • Contacts
  • IM

Searching emails by the specific recipient or sender:

-SearchQuery 'from:"[email protected]" AND to:"[email protected]"'

You can search messages with the specific file as an attachment:

-SearchQuery 'attachment:"annual_report2018.pdf"'

Or by file type:

-SearchQuery 'attachment -like:"*.docx"'

You can search by send/receipt date, but there are some nuances. When using a date as a search criterion, you must consider the regional settings of your Exchange server. For example, April 10, 2019 may be specified in one of the following ways:

  • 10/04/2019
  • 04/10/2019
  • 10-Apr-2019
  • 10/April/2019

And if you see the error “The KQL parser threw an exception…” when running Search-Mailbox command, it means that you are using the wrong date format.

To search for emails sent on a specific day, use this query:

-SearchQuery sent:04/10/2019

If you need to specify the range of dates (you are looking for the messages received in the specified time period):

-SearchQuery {Received:04/01/2019..04/11/2019}

Here is another example. Let’s search the e-mails received before May 9:

-SearchQuery {Received:> $('05/09/2018')}

Search-Mailbox Cmdlet Restrictions

The Search-Mailbox cmdlet has a significant limitation: it can return only 10,000 elements. If this limit is exceeded it will return the error:

Sending data to a remote command failed with the following error message: The total data received from the remote client exceeded allowed maximum. Allowed maximum is 524288000.

Search-Mailbox The total data received from the remote client exceeded allowed maximum

In order to delete more email items, you will have to run Search-Mailbox cmdlet several times or split the mailboxes into groups by mailbox databases or Exchange servers.

Get-Mailbox -Database berl-ex1 | Search-Mailbox –SearchQuery 'from:[email protected]' -DeleteContent –Force

Another Search-Mailbox problem is its low performance. In case of a large company, the search may last for several days.

How to Quickly Find and Delete EMails in Exchange 2016 Using New-ComplianceSearch?

In Exchange 2016, a new way appeared that allows you to quickly find and delete email messages in user mailboxes.

Using these commands, you can significantly narrow the search area:

New-ComplianceSearch -Name FastSearch1 -ExchangeLocation all -ContentMatchQuery 'from:"[email protected]"'
Start-ComplianceSearch -Identity FastSearch1

These commands search through several thousand mailboxes for some minutes.

Next you need to get the list of mailboxes that meet the search criteria:

$search = Get-ComplianceSearch –Identity FastSearch1
$results = $search.SuccessResults
$mbxs = @()
$lines = $results -split '[\r\n]+'
foreach ($line in $lines)
{
if ($line -match 'Location: (\S+),.+Item count: (\d+)' -and $matches[2] -gt 0)
{
$mbxs += $matches[1]
}
}

Now you can remove emails using the Search-Mailbox cmdlet only in the found mailboxes:

$mbxs | Get-Mailbox| Search-Mailbox -SearchQuery 'from:"[email protected]"' -DeleteContent –Force

The total search and delete time is reduced several times, especially in large companies.

Now you can delete the search results:

Remove-ComplianceSearch –Identity FastSearch1

Leave a Reply