Windows OS Hub
  • Windows
    • Windows 11
    • Windows Server 2022
    • Windows 10
    • Windows Server 2019
    • Windows Server 2016
  • Microsoft
    • Active Directory (AD DS)
    • Group Policies (GPOs)
    • Exchange Server
    • Azure and Microsoft 365
    • Microsoft Office
  • Virtualization
    • VMware
    • Hyper-V
  • PowerShell
  • Linux
  • Home
  • About

Windows OS Hub

  • Windows
    • Windows 11
    • Windows Server 2022
    • Windows 10
    • Windows Server 2019
    • Windows Server 2016
  • Microsoft
    • Active Directory (AD DS)
    • Group Policies (GPOs)
    • Exchange Server
    • Azure and Microsoft 365
    • Microsoft Office
  • Virtualization
    • VMware
    • Hyper-V
  • PowerShell
  • Linux

 Windows OS Hub / Exchange / Search and Delete Emails from User Mailboxes on Exchange Server (Microsoft 365) with PowerShell

March 15, 2024 Azure and Microsoft 365ExchangePowerShell

Search and Delete Emails from User Mailboxes on Exchange Server (Microsoft 365) with PowerShell

In Exchange Server, you can use the Search-Mailbox or New-ComplianceSearch PowerShell cmdlets (available in newer versions of Exchange Server and Exchange Online/Microsoft 365) to search for and delete email items from user mailboxes. For example, a user accidentally sent private data to colleagues in the organization and did not have time to recall the message in Outlook. The information security department requires that an Exchange administrator delete this private email from all user mailboxes in your Exchange organization/tenant.

Contents:
  • Permissions Required to Search Exchange Mailboxes
  • Search-Mailbox: Search and Delete Messages from Exchange User Mailboxes
  • Keyword Search Examples for Exchange Mailboxes
  • New-ComplianceSearch: How to Search and Delete Emails in Exchange?

The article applies to on-premises Exchange Server 2019/2016/2013 and 2010, as well as cloud-based Exchange Online (Microsoft 365).  

Permissions Required to Search Exchange Mailboxes

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

  • Mailbox Import Export
  • Mailbox Search

You can assign the roles using EAC or PowerShell. Connect to your on-prem Exchange Server using PowerShell and run the commands:

New-ManagementRoleAssignment -User j.anderson -Role "Mailbox Import Export"
New-ManagementRoleAssignment -User j.anderson -Role "Mailbox Search”

exchange roles: Mailbox Import Export, Mailbox Search

In Exchange Online, you need to assign the following roles:

Add-RoleGroupMember "Discovery Management" -member [email protected]
New-RoleGroup "Mailbox Import-Export Management" -Roles "Mailbox Import Export"
Add-RoleGroupMember "Mailbox Import-Export Management" -Member [email protected]

Add your account to the eDiscovery Admins group in Microsoft 365 Compliance Center

Tip. You can use the Exchange Online PowerShell v3 (EXO V3) module to connect to Exchange Online. 

After the roles have been assigned, restart the PowerShell session.

Search-Mailbox: Search and Delete Messages from Exchange User Mailboxes

You can use the Exchange Admin Center (EAC) web interface or the Search-Mailbox PowerShell cmdlet to search email items in user mailboxes. This command allows you to search for emails in mailboxes by certain criteria, copy the found items to another mailbox, or remove them.

To search a user’s mailbox for emails with a specific subject, run the command:

Search-Mailbox -Identity k.peterson -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"'

When using the Search-Mailbox cmdlet in Exchange Online (Microsoft 365), a warning appears:

WARNING:  On July 1, 2020, the Search-Mailbox cmdlet is being retired and Microsoft Support will no longer provide assistance.  See https://go.microsoft.com/fwlink/?linkid=2113221 to learn more. WARNING: The Search-Mailbox cmdlet returns up to 10000 results per mailbox if a search query is specified. To return more than 10000 results, use the New-MailboxSearch cmdlet or the In-Place eDiscovery & Hold console in the Exchange Administration Center.

Microsoft recommends using the more powerful New-ComplianceSearch and New-ComplianceSearchAction mailbox search cmdlets (discussed below).

To copy the search results to a certain mailbox and folder, use the TargetMailbox or TargetFolder parameters. This will allow you to manually view the found emails in your Outlook after the search is completed. Suppose you need to search for email messages in the list of mailboxes (given in users.txt) and copy the found items to the folder in the specific mailbox:

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

The –LogOnly -LogLevel Full option 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.

exchange search result in csv file

Please note that the received report has the email message Read Status (Read: True/False).

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

Get-Mailbox | Search-Mailbox -SearchQuery 'Subject:"report"' -EstimateResultOnly|select Identity,ResultItemsCount,ResultItemsSize| Where-Object ResultItemsCount -gt 0

exchange: search-mailbox powershell cmdlet result

To delete the found email items, use the –DeleteContent parameter. Add the –Force parameter to skip confirmation prompts

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 –Force

Before removing email items from mailboxes using the -DeleteContent parameter, we strongly recommend that you view found emails using the -EstimateResultOnly or –LogOnly arguments.

Get-Mailbox: DeleteContent parameter

To search only deleted items, 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.

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 items, you will have to run the 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 cmdlet problem is its poor performance. In the case of a large company, the search can take several days. In modern versions of Exchange Server and Microsoft 365, it’s best to use the New-ComplianceSearch cmdlet (discussed below) to search for emails.

Keyword Search Examples for Exchange Mailboxes

Let’s look at examples of search queries to find email items using the SearchQuery parameter. The SearchQuery parameter processes query in the KQL format (Keyword Query Language)  https://docs.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference.

To find and remove all emails containing the keyword “Secret” in the subject from all users not from your domain:

Search-Mailbox -Identity k.peterson -SearchQuery 'Subject:"Secret" and from<>”woshub.com”' -DeleteContent

Using the OR and AND logical operators, you can combine more complex email search conditions.

Find and delete all emails with attachments larger than 20 MB:

Search-Mailbox -Identity k.peterson -SearchQuery 'hasattachment:true AND Size >20971520' –DeleteContent

Tip. The size of the email items is specified in bytes, and the size of the entire email item is counted, not just attachments. You can also specify the size in megabytes. 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 k.peterson -SearchQuery {Subject:"RE:New Year" OR body:"brandy"} -DeleteContent -Force

You can search the mailboxes for specific items using the 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 and sender:

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

  • Emails with attachments : -SearchQuery 'hasattachment:true'
  • Emails that have been read: -SearchQuery 'isread:false'
  • Search emails by size: -SearchQuery 'size>300000'

You can look for messages with the specific file as an attachment:

-SearchQuery 'attachment:"annual_report2021.pdf"'

Or by file type:

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

You can search by send/receipt date, but there are several nuances. When using a date as a search criterion, you must consider the regional settings of your Exchange Server. For example, February 22, 2022 may be specified in one of the following ways:

  • 22/02/2022
  • 02/22/2022
  • 22-Feb-2022
  • 22/February/2022

And if you see the error “The KQL parser threw an exception…” when running the 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:02/22/2022

If you need to specify the range of dates (you are looking for the email items received within a specified time period):

-SearchQuery {Received:01/04/2022..02/20/2022}

Here is another example. Let’s search for emails received after May 9:

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

New-ComplianceSearch: How to Search and Delete Emails in Exchange?

In Exchange 2016/2019 and Exchange Online (Microsoft 365), you can use the new way to quickly search and delete email messages in user mailboxes by using the New-ComplianceSearch and New-ComplianceSearchAction cmdlets.

Microsoft recommends using these cmdlets to search emails in Exchange instead of the deprecated Search-Mailbox command.

Connect to M365 Security & Compliance Center:

Connect-IPPSSession

Let’s try to search mailboxes for emails with a specific subject, sender, and date.

$Sender = "[email protected]"
$StartTime = "02/20/2022"
$EndTime = "02/22/2021"
$Subject = "report2022"

To create an email search task based on the specified criteria, run:

New-ComplianceSearch -Name ContentSearch_Report2022 -ExchangeLocation all -ContentMatchQuery "sent>=$($StartTime) AND sent<=$($EndTime) AND sender:$($Sender) AND subject:$($Subject)"

You can specify search criteria in the -ContentMatchQuery attribute, similar to the -SearchQuery options on the Search-Mailbox cmdlet.

Often at this point an error occurs:

New-ComplianceSearchAction: The term 'New-ComplianceSearchAction' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Verify that you have assigned all Exchange roles as described above.

Close the current PowerShell session and reconnect:

Get-PSSession | Remove-PSSession

To run this job:

Start-ComplianceSearch -Identity ContentSearch_Report2022

You have to wait for it to be done. You can get the current search status like this:

Get-ComplianceSearch -Identity ContentSearch_Report2022| FL name,items,size,jobprogress,status

exchange online get-compliancesearch cmdlet

To print search results to the console in Preview mode:

New-ComplianceSearchAction -SearchName ContentSearch_Report2022 -Preview
(Get-ComplianceSearchAction ContentSearch_Report2022| Select-Object -ExpandProperty Results).Split(";")

If you want to remove all found email items from user mailboxes, use the -Purge option (available in Exchange Online):

New-ComplianceSearchAction -SearchName ContentSearch_Report2022 -Purge -PurgeType SoftDelete

If you want to make deleted emails recoverable by users, use the -PurgeType SoftDelete option. Specify -PurgeType HardDelete to completely remove items from mailboxes.

Now you can delete the search results:

Remove-ComplianceSearch –Identity ContentSearch_Report2022

6 comments
4
Facebook Twitter Google + Pinterest
previous post
How to Reset Windows Update Components to Fix Update Errors
next post
Slow Access to Shared Folders and Network Drives in Windows

Related Reading

View Windows Update History with PowerShell (CMD)

April 30, 2025

Uninstalling Windows Updates via CMD/PowerShell

April 18, 2025

Allowing Ping (ICMP Echo) Responses in Windows Firewall

April 15, 2025

How to Pause (Delay) Update Installation on Windows...

April 11, 2025

How to Write Logs to the Windows Event...

March 3, 2025

6 comments

dauphin September 11, 2021 - 8:41 am

Hello, on exchange 2010 i’m using a command to copy sent items to a PST :

New-MailboxExportRequest -Mailbox domain\bill -ContentFilter “(Sent -LT ‘day/month/year’)” -IncludeFolders “#SentItems#” -FilePath \\MyServer\PSTshare\bill\SentItems.pst

now i would like to delete those sent items from bill’s exchange account to liberate space, what could be the command to achieve that ?

it seems i can’t use Search-Mailbox like in you example because it tells me “The target mailbox or path to the .pst file is required.”,

i just want to delete those emails, not to move them or create another PST file, can you help me please ?

Reply
Mohit February 26, 2022 - 11:54 am

Thank you for your time.

Reply
Miles February 15, 2023 - 5:03 pm

This is perfect, thanks so much

Reply
Dominika March 24, 2023 - 6:49 am

Thank you!

Reply
DSJ January 19, 2024 - 4:19 am

Great writeup – but I’ll add..
The -purge command will only process 10 items at a time per mailbox. It’s designed as an incident response tool, not a wholesale bulk content remover.

Reply
admin January 26, 2024 - 3:13 pm

Thank you, it’s true.👍

Reply

Leave a Comment Cancel Reply

join us telegram channel https://t.me/woshub
Join WindowsHub Telegram channel to get the latest updates!

Categories

  • Active Directory
  • Group Policies
  • Exchange Server
  • Microsoft 365
  • Azure
  • Windows 11
  • Windows 10
  • Windows Server 2022
  • Windows Server 2019
  • Windows Server 2016
  • PowerShell
  • VMware
  • Hyper-V
  • Linux
  • MS Office

Recent Posts

  • Cannot Install Network Adapter Drivers on Windows Server

    April 29, 2025
  • Change BIOS from Legacy to UEFI without Reinstalling Windows

    April 21, 2025
  • How to Prefer IPv4 over IPv6 in Windows Networks

    April 9, 2025
  • Load Drivers from WinPE or Recovery CMD

    March 26, 2025
  • How to Block Common (Weak) Passwords in Active Directory

    March 25, 2025
  • Fix: The referenced assembly could not be found error (0x80073701) on Windows

    March 17, 2025
  • Exclude a Specific User or Computer from Group Policy

    March 12, 2025
  • AD Domain Join: Computer Account Re-use Blocked

    March 11, 2025
  • How to Write Logs to the Windows Event Viewer from PowerShell/CMD

    March 3, 2025
  • How to Hide (Block) a Specific Windows Update

    February 25, 2025

Follow us

  • Facebook
  • Twitter
  • Telegram
Popular Posts
  • Outlook Keeps Asking for Password on Windows
  • Checking User Sign-in Logs in Entra ID (Microsoft 365)
  • How to Manually Configure Exchange or Microsoft 365 Account in Outlook 365/2019/2016
  • Blank Sign-in Screen in Office 365 Apps (Outlook, Teams, etc.)
  • Removing Built-in Teams Chat in Windows 11
  • Fix: Microsoft Outlook Search Not Working on Windows 10/11
  • Export Exchange or Office 365 Global Address List (GAL) to CSV
Footer Logo

@2014 - 2024 - Windows OS Hub. All about operating systems for sysadmins


Back To Top