Using Powershell to delete email in Exchange 2010
Recently I had a request to remove 300,000 or so emails from a users mailbox. Turned out two auto responders got talking to each other, until one of the mailboxes finally filled up and stopped responding. Of course when the user tried to open Outlook, it struggled to download 300,000 message headers and, well, here we are.
This can be used to find/delete one email or thousands of emails. A few weeks after the above happened, an automated alerting system went nuts and sent out about 80,000 emails to 10 or so mailboxes. Again, the below came in handy to zap away the offending emails.
Using Search-Mailbox to search emails
Introducing… the Search-Mailbox cmdlet. This can search for specified criteria and will copy the results to a destination mailbox. First off though, we have to tell Search-Mailbox which mailbox(es) to search – do this using the Get-Mailbox cmdlet.
Get-Mailbox -Identity “UserMailbox To Search” | Search-Mailbox -SearchQuery subject:”This email is SPAM!”,from:”email@example.com” -TargetMailbox “Mailbox to put search results into” -TargetFolder “A folder in that mailbox”
This will search “UserMailbox to search” for any emails with a subject that contains “This email is SPAM!” and from “firstname.lastname@example.org”. If it finds any emails that fit the criteria, then it will copy them all to “Mailbox to put search results into” in the folder “A folder in that mailbox”. Simple huh!
Note – if you leave the -Identity off the Get-Mailbox cmdlet, then it will search EVERY mail box in Exchange. Could be handy, but also be quite slow.
Using Search-Mailbox to delete emails
Now, if you want to delete emails, it’s pretty much the same command, just put a -DeleteContent onto the Search-Mailbox cmdlet and remove the TargetMailbox/TargetFolder options.
Get-Mailbox -Identity “UserMailbox To Search” | Search-Mailbox -SearchQuery subject:”This email is SPAM!”,from:”email@example.com” -DeleteContent
There are a bunch of options you can use with the -SearchQuery option:
|Attachments||attachment:annualreport.pptx||Messages that have an attachment named annualreport.pptx. The use of attachment:annualreport or attachment:annual* returns the same results as using the full name of the attachment.|
|Cc||cc:paul shencc:paulscc:firstname.lastname@example.org||Messages with Paul Shen in the Cc field.|
|From||from:bharat sunejafrom:bsunejafrom:email@example.com||Messages sent by Bharat Suneja.|
|Keywords in retention policy||retentionpolicy:business critical||Messages that have the Business Critical retention tag applied.|
|Date when messages expire according to policy||expires:4/1/2010||Messages that expire on April 1, 2010.|
|Sent||sent:yesterday||All messages sent yesterday.|
|Subject||Subject:”patent filing”||All messages where the phrase “patent filing” appears in the Subject field.|
|To||to:”ben smith”to:bsmithto:firstname.lastname@example.org||Messages that have Ben Smith in the To field|