A frequent operational request for Exchange and Microsoft 365 administrators is purging emails from one specific mailbox folder (such as Deleted Items, Inbox, Junk Email, or a custom alert subfolder like Monitoring Alerts) that arrived between a specific start and end date (FromDate .. ToDate), without touching emails in any other folder.
Historically, administrators used the Exchange Web Services (EWS) Managed API with ApplicationImpersonation and basic authentication to bind to a target folder and call $item.Delete(). However, in Exchange Online:
- Basic Authentication (
WebCredentials) is permanently disabled. ApplicationImpersonationRBAC role and legacy EWS are being retired (see our Exchange Online EWS Retirement & Graph Migration Runbook).- Standard eDiscovery
New-ComplianceSearchsearches the entire mailbox unless you resolve the exactFolderIdtoken.
In this updated guide, we provide both the modern Microsoft Graph PowerShell SDK script (using OData receivedDateTime ge ... and receivedDateTime le ... filtering on a specific MailFolderId with a safe -ReportOnly preview switch) for Exchange Online, as well as the updated EWS Managed API script for on-premises Exchange Server 2016 / 2019 / Exchange SE.
Related Mailbox Cleanup Guides:
- Remove ALL Emails from a Specific Mailbox Folder Using PowerShell
- Delete Email Items and Subfolders or Empty Recoverable Items / Purges via PowerShell
Architecture: Folder-Scoped Date-Range Purge (Microsoft Graph vs. On-Premises EWS)
Method 1: Exchange Online — Remove Emails from a Specific Folder by Date Range via Microsoft Graph PowerShell (Recommended)
In Exchange Online, the modern replacement for EWS impersonation is an Entra ID App Registration (or interactive admin session) granted Mail.ReadWrite (scoped to specific mailboxes via Exchange Online RBAC for Applications so the app only accesses authorized mailboxes).
Save the script below as Remove-GraphFolderEmailsByDate.ps1. By default, if you pass -ReportOnly, it prints and exports the matching emails without deleting anything:
<#
.SYNOPSIS
Deletes or reports emails in a specific Exchange Online mailbox folder between FromDate and ToDate using Microsoft Graph.
.EXAMPLE
.\Remove-GraphFolderEmailsByDate.ps1 -Mailbox "[email protected]" -FolderName "Deleted Items" -FromDate "2026-01-01" -ToDate "2026-03-31" -ReportOnly
.EXAMPLE
.\Remove-GraphFolderEmailsByDate.ps1 -Mailbox "[email protected]" -FolderName "Deleted Items" -FromDate "2026-01-01" -ToDate "2026-03-31" -PermanentDelete
#>
param (
[Parameter(Mandatory = $true)]
[string]$Mailbox,
[Parameter(Mandatory = $true)]
[string]$FolderName = "Deleted Items",
[Parameter(Mandatory = $true)]
[datetime]$FromDate,
[Parameter(Mandatory = $true)]
[datetime]$ToDate,
[switch]$ReportOnly,
[switch]$PermanentDelete
)
# 1. Connect to Microsoft Graph (Supports Unattended Certificate Auth or Interactive Mail.ReadWrite)
if (-not (Get-MgContext)) {
Connect-MgGraph -Scopes "Mail.ReadWrite" -NoWelcome
}
# 2. Format Dates in ISO-8601 UTC format required by Microsoft Graph OData filters
$StartIso = $FromDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
$EndIso = $ToDate.AddDays(1).AddSeconds(-1).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
# 3. Locate the Target Mail Folder (Searches top-level and child folders)
$AllFolders = (Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/users/$Mailbox/mailFolders?`$top=250&includeHiddenFolders=true").value
$TargetFolder = $AllFolders | Where-Object { $_.displayName -eq $FolderName } | Select-Object -First 1
if (-not $TargetFolder) {
# Search one level deeper across child folders
foreach ($Parent in $AllFolders) {
if ($Parent.childFolderCount -gt 0) {
$ChildFolders = (Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/users/$Mailbox/mailFolders/$($Parent.id)/childFolders?`$top=250").value
$Match = $ChildFolders | Where-Object { $_.displayName -eq $FolderName } | Select-Object -First 1
if ($Match) { $TargetFolder = $Match; break }
}
}
}
if (-not $TargetFolder) {
throw "Folder '$FolderName' was not found in mailbox $Mailbox."
}
Write-Host "[+] Bound to Folder: '$($TargetFolder.displayName)' (Total Items in Folder: $($TargetFolder.totalItemCount))" -ForegroundColor Cyan
# 4. Query Messages in Target Folder Between FromDate and ToDate
$Filter = "receivedDateTime ge $StartIso and receivedDateTime le $EndIso"
$Uri = "https://graph.microsoft.com/v1.0/users/$Mailbox/mailFolders/$($TargetFolder.id)/messages?`$filter=$Filter&`$select=id,subject,receivedDateTime,from&`$top=500"
$Messages = [System.Collections.Generic.List[object]]::new()
do {
$Page = Invoke-MgGraphRequest -Method GET -Uri $Uri
if ($Page.value) { $Messages.AddRange($Page.value) }
$Uri = $Page.'@odata.nextLink'
} while ($Uri)
Write-Host "[+] Found $($Messages.Count) email(s) in '$FolderName' between $StartIso and $EndIso" -ForegroundColor Yellow
if ($ReportOnly -or $Messages.Count -eq 0) {
$Messages | ForEach-Object {
[PSCustomObject]@{
ReceivedDateTime = $_.receivedDateTime
Sender = $_.from.emailAddress.address
Subject = $_.subject
MessageId = $_.id
}
} | Format-Table -AutoSize
return
}
# 5. Delete Matching Messages
$DeletedCount = 0
foreach ($Msg in $Messages) {
try {
if ($PermanentDelete) {
# HardDelete: Moves item directly to Recoverable Items (Purges/Deletions) bypassing Deleted Items
Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/users/$Mailbox/messages/$($Msg.id)/permanentDelete"
} else {
# Standard Delete: Removes message resource
Invoke-MgGraphRequest -Method DELETE -Uri "https://graph.microsoft.com/v1.0/users/$Mailbox/mailFolders/$($TargetFolder.id)/messages/$($Msg.id)"
}
$DeletedCount++
Write-Host "[$DeletedCount/$($Messages.Count)] Deleted: $($Msg.subject) ($($Msg.receivedDateTime))" -ForegroundColor Green
} catch {
Write-Warning "Failed to delete message '$($Msg.subject)': $($_.Exception.Message)"
}
}
Write-Host "[✔] Completed: $DeletedCount email(s) deleted from '$FolderName' in $Mailbox." -ForegroundColor Green
Method 2: On-Premises Exchange Server (2016 / 2019 / SE) — EWS Managed API Date-Range Script
If you are managing an on-premises Exchange Server where the EWS Managed API (Microsoft.Exchange.WebServices.dll) and ApplicationImpersonation remain supported, use strongly typed SearchFilter+SearchFilterCollection date comparisons (which avoid locale-specific MM/dd/yyyy string parsing bugs in AQS queries):
param (
[string]$AdminUser = $cred.UserName,
[string]$Pass = $cred.GetNetworkCredential().Password,
[string]$MailboxToImpersonate = "[email protected]",
[string]$Folder = "Deleted Items",
[datetime]$FromDate = "2026-03-01",
[datetime]$ToDate = "2026-03-30",
[int]$PageSize = 1000,
[string]$EwsUrl = "https://mail.lab365.in/EWS/Exchange.asmx",
[switch]$Report
)
# 1. Load EWS Managed API 2.0 Assembly
$EWSServicePath = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
Import-Module $EWSServicePath
$ExchVer = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1
$Service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchVer)
$Service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($AdminUser, $Pass)
$Service.Url = [uri]$EwsUrl
# 2. Configure EWS Impersonation for Target Mailbox
$Service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId(
[Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,
$MailboxToImpersonate
)
# 3. Bind to MsgFolderRoot and Perform Deep Traversal for Target Folder Name
$MailboxRootId = New-Object Microsoft.Exchange.WebServices.Data.FolderId(
[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,
$MailboxToImpersonate
)
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($Service, $MailboxRootId)
$FolderView = New-Object Microsoft.Exchange.WebServices.Data.FolderView(10)
$FolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep
$FolderFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo(
[Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,
$Folder
)
$FolderResults = $MailboxRoot.FindFolders($FolderFilter, $FolderView)
if ($FolderResults.TotalCount -eq 0) {
throw "Folder '$Folder' not found in mailbox $MailboxToImpersonate"
}
$TargetFolder = $FolderResults.Folders[0]
# 4. Build Strongly-Typed DateTimeReceived SearchFilter Collection
$FilterStart = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsGreaterThanOrEqualTo(
[Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived,
$FromDate
)
$FilterEnd = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsLessThanOrEqualTo(
[Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived,
$ToDate.AddDays(1).AddSeconds(-1)
)
$DateRangeFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection(
[Microsoft.Exchange.WebServices.Data.LogicalOperator]::And,
@($FilterStart, $FilterEnd)
)
$ItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView($PageSize)
$FindItemResults = $TargetFolder.FindItems($DateRangeFilter, $ItemView)
Write-Host "Folder: $($TargetFolder.DisplayName) | Matching Items Found: $($FindItemResults.TotalCount) between $($FromDate.ToShortDateString()) and $($ToDate.ToShortDateString())" -ForegroundColor Cyan
if ($Report) {
$FindItemResults.Items | Select-Object Subject, DateTimeReceived, Sender | Format-Table -AutoSize
} else {
$Deleted = 0
foreach ($Item in $FindItemResults.Items) {
try {
[void]$Item.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::HardDelete)
$Deleted++
Write-Host "[$Deleted] Hard-deleted: $($Item.Subject)" -ForegroundColor Green
} catch {
Write-Warning "Unable to delete item '$($Item.Subject)': $($_.Exception.Message)"
}
}
Write-Host "[✔] Total items hard-deleted from '$Folder': $Deleted" -ForegroundColor Green
}