Saturday, January 14, 2017

Exchange Search-Mailbox Delete More Than 10,000 Items

A few days ago one of my buddies (who happens to be running the Exchange 2013 environment at my old job) called and had a problem where a user got spammed with 13,000,000 messages. Yes, you read that correctly, that's 13 million!
Normally, you would run the Search-Mailbox cmdlet with the -DeleteContent switch to clear those out.
The problem here is, the Search-Mailbox command is limited to only 10,000 messages, and you would have re-run it until you clear out the mailbox...with 13 million, you'd be running that cmdlet a ton of times!

So I created a quick and dirty script that will loop the Search-Mailbox until it doesn't find any more instances of the message.

Copy and paste the following code into notepad and save it as a .ps1 file. For instance Delete-HugeSpam.ps1

$mbx = get-mailbox "mailboxname here"

Do {
 $result = Search-Mailbox -Identity $mbx.Identity -SearchQuery 'Subject:"this is spam from a dirty spammer"' -DeleteContent -force -WarningAction Silentlycontinue

write-host $result.resultitemscount -ForegroundColor Green

 } Until ($result.resultitemscount -eq 0)

**Note** Change "mailboxname here" to the mailbox with all the spam, and "this is spam from a dirty spammer" to whatever the Subject of the message is.

Once you have the .ps1 file configured with your mailbox name and subject, fire up the Exchange Management Shell (EMS),  and cd to the directory where you saved the .ps1, then run:


You can monitor the mailbox from OWA by giving yourself FullAccess. I wouldn't recommend using Outlook if there's thousands or millions (in this case) of items because it'll prolly never open.
You should then see the message count doing down.

Now, instruct your user not to open suspicious emails, or better yet don't allow them to have a mailbox anymore :)