Wednesday, 13 February 2013
Using Powershell to delete email in Exchange 2010
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.
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.
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:
Source - http://technet.microsoft.com/en-us/library/bb232132.aspx#AQS