PowerShell – Search-Mailbox script to go through all mailboxes, find a target message, and remove it

When looking at the title of this post, one might notice I used a target word, and it is on purpose. This script below is useful when trying to remove all types of messages from users’ mailboxes whether it’s a spam, scam, virus or a an important message that needs to be “recalled”.

This script is based on Search-Mailbox cmdlet, works well but it has its own pros and cons, more on some of them below.

Later I will have another post showing a different and more advanced script to do the same and even better. So stay tuned.

Pros:

Cons:

  • Per Microsoft Search-Mailbox will be depreciated, we don’t know when it will happen though.
  • Slow (if a target message is in every mailbox, then it will take about 20 minutes to run through 100 mailboxes and remove that message).

Don’t forget to replace ithelp@contoso.com with an email address of your IT Help or any other mailbox (!).

$fromemail = Read-Host "From (email)"
$subject = Read-Host "Part of the subject line"
$date = Read-Host "Date (e.g. 'No preceding Zeros in date' 7/11/2018 - the search will go through [Your entered date]...[Todays Date] time window)"

If ($fromemail -eq '') {
	$Query = "Subject:""*" + $subject + "*"" received>=" + $date
}

ElseIf ($subject -eq '') {
	$Query = "From:" + $fromemail + " received>=" + $date
}
	
Else {
	$Query = "From:""" + $fromemail + """ Subject:""*" + $subject + "*"" received>=" + $date
}
   
$Mailboxes = Get-Mailbox -ResultSize unlimited | Where-Object {$_.recipienttypedetails -ne "RoomMailbox" -and $_.recipienttypedetails -ne "EquipmentMailbox"}

$FilteredResults = ForEach ($Mailbox in $Mailboxes)	{
	Search-Mailbox -Identity $Mailbox.DisplayName -SearchQuery $Query -SearchDumpster -EstimateResultOnly | Where-Object {$_.ResultItemsCount -gt 0}
}	

Write-host "List of mailboxes matching the search criteria:"
$FilteredResults | fl
	
$Answer = Read-Host "Would you like to move those messages from listed above mailboxes into IT Help mailbox - Check folder (y / n)?"
while("y","n" -notcontains $answer) {$answer = Read-Host "Would you like to move those messages from listed above mailboxes into IT Help mailbox - Check folder (y / n)?"}

If ($answer -eq 'y') {
	
	ForEach ($Result in $FilteredResults) {
		Search-Mailbox -Identity $Result.Identity -SearchQuery $Query -SearchDumpster -TargetMailbox ithelp@contoso.com -TargetFolder Check -DeleteContent -Confirm:$false -Force
	}
	
	Remove-Variable * -ErrorAction SilentlyContinue
	
}

Else {
	Remove-Variable * -ErrorAction SilentlyContinue
}

This Post Has One Comment

Leave a Reply