I see a lot of posts of people asking how to delete certain e-mails from their users’ mailboxes.
It is very simple and it is done using the Export-Mailbox command.
Imagine that we want to delete e-mails from firstname.lastname@example.org from any of my folders. In this case we would simply do:
Export-Mailbox email@example.com -SenderKeywords firstname.lastname@example.org -DeleteContent
Because you are not using the –TargetMailbox option and we are using –DeleteContent, all the e-mails that match the search criteria won’t be exported to anywhere but actually deleted.
But, of course, we can do searches a lot more complex. For example, let’s delete:
- all e-mails from every folder except the Deleted Items folder
- that were sent from email@example.com with the subject “Test E-mail”
- and that are older than one month:
[DateTime] $date1Month = [DateTime]::Now.AddMonths(-1)
Export-Mailbox firstname.lastname@example.org -SenderKeywords email@example.com -SubjectKeywords "Test E-mail" -EndDate $date1Month -ExcludeFolders "\Deleted Items" -DeleteContent -Confirm:$False
If you are doing this on a script for a list of users, you can also do something like:
$strDeleted = Export-Mailbox $strMbxToSearch -SenderKeywords firstname.lastname@example.org -SubjectKeywords "Test E-mail" -EndDate $date1Month -ExcludeFolders "\Deleted Items" -DeleteContent -Confirm:$False
$intTotalDel = $strDeleted.StandardMessagesDeleted
Write-Host "Searched $strMbxToSearch and deleted $intTotalDel"
Note that all the deleted e-mails will go to the user’s dumpster, not to the Deleted Items folder.