Emails in Exchange Online can be removed in a variety of ways. Not all of the methods remove emails in the same fashion:
Exchange Online
Search-Mailbox
• This cmdlet allows for permanent deletion, moving messages to another mailbox or logging only.
• Limit of 10,000 results
New-MailboxSearch
• No way to delete content, only good for searching and sending the searches to target mailbox
Security and Compliance Center
New-ComplianceSearch / New-ComplianceSearchAction
• This cmdlet allows for options like SoftDelete
• Caveat to this is that it is limited to clearing 10 items at a time – we’ll explore a solution for this down below.
Example Usage
Let’s take a sample scenario where there is mailbox cleanup needed. Overtime some formerly wanted emails are no longer wanted. The goal is to take messages with a known sender and subject and remove them from the mailbox. However, if mistakes are made there needs to be a way to recover these emails by the end user. This would require a soft-delete of the message and not a hard-delete.
From our choice of cmdlets – Search-Mailbox, New-MailboxSearch and New-ComplianceSearch. Of these, only the first and last can remove messages. Further filtering, only the last option (New-ComplianceSearch) has the option for SoftDelete. As noted above, this can only be run from a PowerShell session in the Security and Compliance Center.
Security and Compliance Center (SCC) Solution
First Step – Connect to the SCC
$LiveCred = Get-Credential $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $LiveCred -Authentication Basic -AllowRedirection Import-PSSession $Session
Second Step – Kicking off a search:
$Sender = "alias@domain.com" $Subject = "Unwanted Email" New-ComplianceSearch -Name $Search -ExchangeLocation $Mailbox -ContentMatchQuery "subject:$Subject AND from:$Sender" Start-ComplianceSearch -Identity $Search $Items = (Get-ComplianceSearch -Identity $Search).Items New-ComplianceSearchAction -SearchName $Search -Purge -PurgeType SoftDelete -Confirm:$False
The key to the removal process is ‘-Purge‘ and ‘-PurgeType SoftDelete‘. These parameters are what tells the search to simply soft delete the messages that are found. There are know limitations as stated above with a limit of 10 emails that can be removed. This limit can be overcome with a loop to remove messages until no more are found. Something to keep in mind if you need to remove messages in this manner.
Further Reading
New-ComplianceSearchAction
Start-ComplianceSearch
New-ComplianceSearch