This can be used to find/delete one email or thousands of emails. 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:”firstname.lastname@example.org” -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 “email@example.com”. 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:”firstname.lastname@example.org” -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:email@example.com||Messages with Paul Shen in the Cc field.|
|From||from:bharat sunejafrom:bsunejafrom:firstname.lastname@example.org||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:email@example.com||Messages that have Ben Smith in the To field|