Mass Phishing Cleanup Script for On-Premises Exchange

In enterprise environments, phishing campaigns can impact hundreds or thousands of mailboxes within minutes. Once malicious emails are delivered, administrators must respond quickly and remove them centrally.

This article presents a production-ready PowerShell script designed for bulk phishing email removal across all user mailboxes in on-premises Exchange environments.

The script is intended for:

  • Microsoft Exchange Server 2010
  • Microsoft Exchange Server 2016
  • Microsoft Exchange Server 2019

This solution is specifically for on-premises deployments (not Exchange Online).

The Script

# ================================
# CONFIGURATION
# ================================

# Inline spam sender list
$senders = @(
    "somespam@gmail.com",
    "anotherspam@gmail.com",
    "yetanotherspam@gmail.com"
)

# Generate timestamped log file name
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$LogPath = "C:\spam_cleanup_$timestamp.csv"

# ================================
# BUILD SEARCH QUERY
# ================================

$SearchQuery = ($senders | ForEach-Object { "From:`"$_`"" }) -join " OR "

Write-Host "SearchQuery:"
Write-Host $SearchQuery
Write-Host ""

# ================================
# CREATE CSV HEADER
# ================================

"Date,Mailbox,DeletedItems" | Out-File $LogPath -Encoding UTF8

# ================================
# GET USER MAILBOXES ONLY
# ================================

$mailboxes = Get-Mailbox -ResultSize Unlimited -RecipientTypeDetails UserMailbox

# ================================
# MAIN LOOP
# ================================

foreach ($mb in $mailboxes) {

    $MailboxDN = $mb.DistinguishedName
    $MailboxAddress = $mb.PrimarySmtpAddress.ToString()

    Write-Host "Processing: $MailboxAddress" -ForegroundColor Cyan

    try {
        $result = Search-Mailbox `
            -Identity $MailboxDN `
            -SearchQuery $SearchQuery `
            -DeleteContent `
            -Force `
            -ErrorAction Stop

        $deleted = $result.ResultItemsCount

        if ($deleted -gt 0) {
            $logLine = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'),$MailboxAddress,$deleted"
            Add-Content -Path $LogPath -Value $logLine
            Write-Host "Deleted: $deleted" -ForegroundColor Green
        }
        else {
            Write-Host "Nothing found"
        }
    }
    catch {
        Write-Host "Error processing $MailboxAddress" -ForegroundColor Red
    }
}

Write-Host ""
Write-Host "Completed."
Write-Host "Log file: $LogPath"

Why This Approach Is Relevant for On-Prem Exchange

Exchange 2010

Search-Mailbox is the native and primary tool for eDiscovery and bulk mailbox operations. It remains the fastest built-in method for mass deletion.

Exchange 2016

The cmdlet is fully supported and remains highly effective for operational incident response scenarios.

Exchange 2019

Although Microsoft promotes ComplianceSearch for discovery scenarios, for urgent phishing cleanup:

  • Search-Mailbox is faster to execute
  • does not require search object lifecycle management
  • avoids compliance pipeline overhead
  • provides predictable operational behavior

For real-time incident response, simplicity and speed are critical.

Why Not Use ComplianceSearch?

Cmdlets such as:

  • New-ComplianceSearch
  • New-ComplianceSearchAction

are designed primarily for:

  • legal investigations
  • audit scenarios
  • long-term evidence retention
  • compliance workflows

They are not optimized for rapid phishing cleanup because they:

  • require creating search jobs
  • operate asynchronously
  • introduce additional management complexity
  • may increase execution time in large environments

For on-prem incident response, direct mailbox search remains more efficient.

How the Script Works

Configuration Block

The administrator defines a list of malicious senders directly in the script. This allows immediate response during an incident without external dependencies.

A timestamped log file is generated automatically, ensuring each execution is documented.

Query Construction

The script builds a single optimized query:

From:"sender1@gmail.com" OR From:"sender2@gmail.com"

This approach:

  • avoids multiple search passes
  • reduces execution time
  • minimizes Content Index load
  • scales better in large environments

Mailbox Scope Limitation

The script targets only:

RecipientTypeDetails UserMailbox

This excludes:

  • arbitration mailboxes
  • discovery mailboxes
  • system mailboxes
  • public folder mailboxes

This improves reliability and avoids unnecessary processing.

Why DistinguishedName Is Used Instead of Alias

Using:

  • Alias
  • DisplayName
  • Short Identity strings

can lead to:

ManagementObjectAmbiguousException

This occurs when multiple directory objects match the provided identity (e.g., soft-deleted mailboxes, duplicate aliases, disabled accounts).

DistinguishedName is:

  • globally unique within Active Directory
  • unambiguous
  • safe for enterprise environments

For production-grade scripting, DN should always be preferred.

Deletion Execution

Search-Mailbox:

  • performs a Content Index search
  • deletes matched messages immediately
  • returns the number of deleted items

This provides both speed and immediate remediation.

Logging

The script generates a CSV report containing:

  • Date
  • Mailbox
  • DeletedItems

This allows:

  • incident documentation
  • impact assessment
  • management reporting
  • forensic reference

Leave a Comment