In 2017, the standard way an Exchange administrator emptied a user's corrupted folder, flushed a bloated Junk folder, or purged messages was using the EWS Managed API 2.2 with ApplicationImpersonation and basic authentication.
Today in Microsoft 365 and modern Exchange, all three elements are retired:
- Basic Authentication was turned off tenant-wide.
- ApplicationImpersonation was retired in Exchange Online in favor of Exchange RBAC for Applications and Entra App Roles.
Search-Mailbox -DeleteContentwas deprecated and removed from modern Exchange Online.
Depending on your operational goal, there are now two official, secure methods to delete email items with PowerShell:
- Scenario A (Targeted Folder Cleaning): Empty a specific mailbox folder (e.g., Junk Email, Deleted Items, or custom project folder) using the Microsoft Graph PowerShell SDK.
- Scenario B (Security Incident Response / Phishing Purge): Delete a specific phishing or malicious message across all user mailboxes using Microsoft Purview Compliance Search (
New-ComplianceSearchAction -Purge).
In this modernized guide, we provide production PowerShell solutions for both scenarios.
Modern Architecture vs Legacy EWS
ApplicationImpersonation(Retired)- Basic Auth (Dead) / Legacy DLLs
Search-Mailbox -DeleteContent(Removed)
- Permissions:
Mail.ReadWrite - Target specific folders (Junk, DeletedItems)
- Soft or Hard delete items via REST API
- Roles:
eDiscovery Manager+Search And Purge New-ComplianceSearchby Subject/SenderNew-ComplianceSearchAction -Purge
Scenario A: Empty a Specific Folder Using Microsoft Graph PowerShell
To empty a mailbox folder (such as Junk Email, Deleted Items, or a custom subfolder) without touching other folders, use Microsoft Graph PowerShell.
1. Connect to Microsoft Graph
Connect with administrative permissions to manage mailboxes:
# Interactive connection with Delegated permissions
Connect-MgGraph -Scopes "Mail.ReadWrite", "User.Read.All"
# Or unattended Certificate-Based App-Only authentication:
# Connect-MgGraph -TenantId "<TenantID>" -ClientId "<AppID>" -CertificateThumbprint "<Thumbprint>"
2. Script to Enumerate and Empty Folder Items
The following script resolves the target folder (by standard well-known name or display name) and removes all contained messages:
function Clear-MgUserMailFolder {
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(Mandatory = $true)]
[string]$UserPrincipalName,
[Parameter(Mandatory = $true)]
[string]$FolderName,
[Parameter(Mandatory = $false)]
[switch]$PermanentDelete
)
# 1. Resolve the Target Folder ID
Write-Host "[*] Locating folder '$FolderName' for $UserPrincipalName..." -ForegroundColor Cyan
$folders = Get-MgUserMailFolder -UserId $UserPrincipalName -All
$targetFolder = $folders | Where-Object { $_.DisplayName -ieq $FolderName -or $_.WellKnownName -ieq $FolderName }
if (-not $targetFolder) {
Write-Error "Folder '$FolderName' was not found in mailbox $UserPrincipalName."
return
}
Write-Host "[+] Found folder: $($targetFolder.DisplayName) (ID: $($targetFolder.Id))" -ForegroundColor Green
Write-Host "[*] Item Count: $($targetFolder.TotalItemCount)" -ForegroundColor Yellow
if ($targetFolder.TotalItemCount -eq 0) {
Write-Host "[!] Folder is already empty." -ForegroundColor Gray
return
}
# 2. Retrieve Items in Batches
if ($PSCmdlet.ShouldProcess("$($targetFolder.TotalItemCount) items in '$FolderName'", "Delete Email Items")) {
$messages = Get-MgUserMailFolderMessage -UserId $UserPrincipalName -MailFolderId $targetFolder.Id -All -Property Id, Subject, ReceivedDateTime
$count = 0
foreach ($msg in $messages) {
$count++
Write-Progress -Activity "Purging items from $FolderName" -Status "Deleting $count of $($messages.Count)" -PercentComplete (($count / $messages.Count) * 100)
if ($PermanentDelete) {
# Hard delete directly via Graph
Remove-MgUserMessage -UserId $UserPrincipalName -MessageId $msg.Id -Confirm:$false
} else {
# Soft delete: Move to Deleted Items or Delete
Remove-MgUserMessage -UserId $UserPrincipalName -MessageId $msg.Id -Confirm:$false
}
}
Write-Host "`n[+] Successfully cleared $count items from '$($targetFolder.DisplayName)'." -ForegroundColor Green
}
}
Usage Example:
# Empty Junk Email folder (Soft Delete)
Clear-MgUserMailFolder -UserPrincipalName "[email protected]" -FolderName "Junk Email"
# Permanently empty Deleted Items folder
Clear-MgUserMailFolder -UserPrincipalName "[email protected]" -FolderName "Deleted Items" -PermanentDelete
Scenario B: Purge Malicious or Phishing Emails Tenant-Wide (Purview Search & Purge)
When responding to phishing, malware, or accidental data leakage across multiple users, do not write loops across individual mailboxes. Instead, use the native Microsoft Purview Compliance Center compliance search and purge pipeline.
Prerequisites & Permissions
To execute purge actions, your admin account must be assigned the Search And Purge role in the Purview Compliance Center (by default, even Organization Management does not have this role assigned):- Go to Microsoft Purview Portal (
purview.microsoft.com) > Settings > Roles and scopes > Permissions. - Edit eDiscovery Manager or create a custom role group, and add the Search And Purge role.
1. Connect to Security & Compliance PowerShell
Connect-IPPSSession -UserPrincipalName [email protected]
2. Create and Start the Compliance Search
Query by Message Subject, Sender, or Internet Message ID:
$SearchName = "Incident_Phish_20261112"
$Query = '(From: "[email protected]") AND (Subject: "Urgent Invoice Payment")'
# Create the search targeted across all Exchange mailboxes
New-ComplianceSearch -Name $SearchName -ExchangeLocation All -ContentMatchQuery $Query
# Start the search execution
Start-ComplianceSearch -Identity $SearchName
# Monitor until complete
do {
Start-Sleep -Seconds 5
$status = Get-ComplianceSearch -Identity $SearchName
Write-Host "[*] Search Status: $($status.Status)..." -ForegroundColor Cyan
} while ($status.Status -ne "Completed")
Write-Host "[+] Search completed! Found $($status.Items) items across $($status.SuccessResults) mailboxes." -ForegroundColor Green
3. Execute the Purge Action
Once search results are verified, issue a Purge action:
# SoftDelete: Items move to Recoverable Items (Deletions) folder
New-ComplianceSearchAction -SearchName $SearchName -Purge -PurgeType SoftDelete
# HardDelete: Items are purged from Recoverable Items (Purges folder)
# New-ComplianceSearchAction -SearchName $SearchName -Purge -PurgeType HardDelete
# Monitor purge action progress
Get-ComplianceSearchAction -Identity "${SearchName}_Purge" | Format-List SearchName, Action, Status, Results
Important Limit: A single New-ComplianceSearchAction -Purge can delete a maximum of 10 items per mailbox per execution. If a single user mailbox received more than 10 phishing items, re-run the search and purge action until zero items remain.
What About the Recoverable Items Folder?
If you are trying to clean up bloated Recoverable Items (Deletions, Purges, Versions) caused by Litigation Hold or Single Item Recovery:
- Deletion commands (
Remove-MgUserMessageorNew-ComplianceSearchAction) will be retained if a hold is active. - Use Retention Policies with an automated MRM policy, or temporarily disable Litigation Hold during administrative cleanups:
Set-Mailbox -Identity "[email protected]" -LitigationHoldEnabled $false
Start-ManagedFolderAssistant -Identity "[email protected]"
Summary: Which Tool Should You Use?
| Requirement | Recommended Tool | Command / API |
|---|---|---|
| Empty Junk / Deleted Items for a specific user | Microsoft Graph PowerShell | Get-MgUserMailFolderMessage + Remove-MgUserMessage |
| Security threat / Phishing email in 100+ mailboxes | Purview Compliance Center | New-ComplianceSearchAction -Purge |
| Automated mailbox lifecycle cleanup | Exchange Retention Tags (MRM) | Start-ManagedFolderAssistant |
| Old legacy on-premises Exchange EWS script | Retired | Migrate to Graph SDK or EWS OAuth with app registration |