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!"
Pause
$MessageSubject = Read-Host "Enter Subject of the Message to be Deleted"
$UserCredential = Get-Credential
	$ExchangeOnline = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -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
	}
	

About Kevin Trent

IT professional with almost 30 years of experience in Infrastructure, Architecting, Administration, Development, and Communications.

Leave a Reply

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

WordPress.com Logo

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s