Remove a Message from All Office 365 Mailboxes

Nefarious characters are using the pandemic as a weapon. They’re sending emails to your employees with subjects and content that make them think it is important news or instructions. If your email is hosted by Office 365 the following script will permanently delete a message by subject from all mailboxes.

Paste the text below into your favorite text editor and save it with the .ps1 extension. When you are ready to run it, right click on the file and choose “Run with PowerShell”. Enter your Office 365 credentials and the subject of the message when prompted.

# RemoveMessage-Office365Mailboxes
Write-Host "This script will permanently delete a message from all Office 365 mailboxes. Use with caution!"
$MessageSubject = Read-Host "Enter Subject of the Message to be Deleted"
$UserCredential = Get-Credential
	$ExchangeOnline = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri -Credential $UserCredential -Authentication Basic -AllowRedirection
	Import-PSSession $ExchangeOnline
$mailboxusers = Get-Mailbox -ResultSize Unlimited

Foreach ($user in $mailboxusers)
		Search-Mailbox -Identity $user.alias -SearchQuery 'Subject:$MessageSubject' -DeleteContent -Force

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s