How to Use Search-Mailbox to Remove Mailbox Items

MagTapes

Updated 15 September 2021

Note: Formal support from Microsoft for the Search-Mailbox cmdlet ceased on July 1, 2020. See this post for more information. As of September 15, 2021, the cmdlet is still available.

In a previous post about the Search-Mailbox cmdlet, I discussed how the cmdlet is restricted to only processing Exchange user and shared mailboxes. Some questions came in about how easy is it to delete items from mailboxes with Search-Mailbox. The answer is that it’s terrifically easy.

Blowing Messages Away

For example, this command searches all user mailboxes to find messages with “Spam Email” in the message subject and deletes any matching items. The deleted items are irrecoverable.

Get-ExoMailbox -RecipientTypeDetails UserMailbox -ResultSize Unlimited | Search-Mailbox -SearchQuery {Subject: "Spam Email" Received:1-Apr-2018..1-Jul-2024} -DeleteContent

A much more comprehensive parameter-driven example is described in this article. The script used in the article can search based on message subject, body text, author, and date range, which is a more realistic example of the kind of thing that administrators need to do.

It’s easy to see how mistakes could be made and many items removed from user mailboxes in the twink of an eye. Well, Search-Mailbox doesn’t run so quickly, so maybe several twinks of the eye.

The Same Problem a Long Time Ago

Having a function that can wreak havoc on mailbox contents is not unique to Exchange. In the past, when I worked on Digital Equipment Corporation’s ALL-IN-1 Office system in the early 1990s, we had a problem with an internal system in Turin, Italy, when the administrator ran a script to do mailbox maintenance. He thought that any mail older than a year would be removed, but a mistake in syntax meant that every single message in every single mailbox was removed. No one realized until Monday morning when howls of pain erupted after people discovered what had happened to their mailboxes.

In those days, we could restore mailboxes (and the databases used to connect messages together) from large 1600 bpi magnetic tapes like those shown above. Today, if you run Search-Mailbox and use the DeleteContent switch to remove items from Exchange Online, you won’t have any type of backup to fall back on – unless you buy a third-party cloud backup service.

Be careful!

Read more about Search-Mailbox in Chapter 6 of Office 365 for IT Pros.

7 Replies to “How to Use Search-Mailbox to Remove Mailbox Items”

    1. If the mailbox is under litigation hold, the items will be removed from user view but captured in the Recoverable Items structure.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.