Remove All Emails from a Specific Mailbox Folder Using PowerShell (Microsoft Graph $batch & EWS)

When a monitoring alert storm, runaway mail flow loop, or retention backlog floods a specific folder inside a user or shared mailbox (for example, \Deleted Items, \Junk Email, or a nested subfolder like \Inbox\Automated Reports), administrators need a fast, surgical way to empty all emails from that specific folder without affecting the rest of the mailbox.

While our companion guide—Remove Emails from a Specific Mailbox Folder Between a Date Range Using PowerShell—filters messages by receivedDateTime, this runbook focuses on resolving nested folder paths (\Parent\Child) and purging 100% of items inside the target folder.

Because Microsoft has retired Basic Authentication and is shutting down Exchange Web Services (EWS) in Exchange Online (see our Exchange Online EWS Retirement & Graph Migration Guide), we provide:

  1. The Modern Microsoft Graph JSON $batch Script for Exchange Online (which deletes up to 20 messages per HTTP request to avoid throttling on folders with 10,000+ items).
  2. The On-Premises Exchange Server EWS Script (including Folder.Empty() and recursive path resolution for Exchange 2016 / 2019 / Exchange SE).

Architecture: Emptying a Specific Mailbox Folder at Scale

Bulk Folder Purge Architecture: Microsoft Graph JSON $batch vs. On-Premises EWS Folder.Empty() Exchange Online: Microsoft Graph $batch • Path-to-FolderId Traversal: Walks \Inbox\Alerts -> childFolders • High-Speed 20-Item JSON Batching: POST https://graph.microsoft.com/v1.0/$batch - 20x faster than single-item DELETE loops - Supports permanentDelete or standard DELETE ✔ EWS-Free & App-Only Certificate Compatible On-Premises Exchange: EWS Folder.Empty() • Recursive GetFolder() Path Resolver: Splits "\Inbox\Subfolder" by "\" • Instant Server-Side Empty Call: $FolderObject.Empty([DeleteMode]::HardDelete, $false) - Or paged ItemView(1000) loop for item logging - Second parameter ($false) preserves subfolders ✔ Ideal for Exchange 2016 / 2019 / Exchange SE When to Use `Folder.Empty()` vs. Item-by-Item Deletion: • If you do not need an item-by-item subject log on on-premises Exchange, `$FolderObject.Empty([DeleteMode]::HardDelete, $false)` empties the folder in one server operation. • In Exchange Online (Microsoft Graph), use the `$batch` endpoint below to purge 20 messages per HTTP call cleanly.

Method 1: Exchange Online — Empty a Specific Folder Using Microsoft Graph PowerShell ($batch)

This script resolves any top-level or nested folder path (such as \Deleted Items or \Inbox\Alerts\SQL) and purges all messages inside it using Microsoft Graph JSON Batching (POST /v1.0/$batch) in chunks of 20 items per request:

POWERSHELL
<#
.SYNOPSIS
    Empties all emails from a specific folder path (e.g. "\Deleted Items" or "\Inbox\Alerts") in Exchange Online via Microsoft Graph.
#>
param (
    [Parameter(Mandatory = $true)]
    [string]$Mailbox = "[email protected]",

    [Parameter(Mandatory = $true)]
    [string]$FolderPath = "\Deleted Items",

    [switch]$WhatIfReportOnly
)

# 1. Connect to Microsoft Graph
if (-not (Get-MgContext)) {
    Connect-MgGraph -Scopes "Mail.ReadWrite" -NoWelcome
}

# 2. Walk the Folder Path (e.g., "\Inbox\Subfolder1\Subfolder2")
$PathSegments = $FolderPath.Trim('\') -split '\\' | Where-Object { $_ }
$CurrentFolder = $null

for ($i = 0; $i -lt $PathSegments.Count; $i++) {
    $SegmentName = $PathSegments[$i]
    if ($i -eq 0) {
        $Folders = (Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/users/$Mailbox/mailFolders?`$top=250&includeHiddenFolders=true").value
    } else {
        $Folders = (Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/users/$Mailbox/mailFolders/$($CurrentFolder.id)/childFolders?`$top=250").value
    }

    $CurrentFolder = $Folders | Where-Object { $_.displayName -eq $SegmentName } | Select-Object -First 1
    if (-not $CurrentFolder) {
        throw "Failed to find folder segment '$SegmentName' in requested path '$FolderPath'."
    }
}

Write-Host "[+] Resolved Folder Path '$FolderPath' -> FolderId: $($CurrentFolder.id) (Items: $($CurrentFolder.totalItemCount))" -ForegroundColor Cyan

# 3. Fetch All Message IDs in the Target Folder
$Messages = [System.Collections.Generic.List[object]]::new()
$Uri = "https://graph.microsoft.com/v1.0/users/$Mailbox/mailFolders/$($CurrentFolder.id)/messages?`$select=id,subject,receivedDateTime&`$top=500"

do {
    $Resp = Invoke-MgGraphRequest -Method GET -Uri $Uri
    if ($Resp.value) { $Messages.AddRange($Resp.value) }
    $Uri = $Resp.'@odata.nextLink'
} while ($Uri)

Write-Host "[+] Retrieved $($Messages.Count) total messages from '$FolderPath'." -ForegroundColor Yellow

if ($WhatIfReportOnly -or $Messages.Count -eq 0) {
    $Messages | Select-Object -First 25 receivedDateTime, subject, id | Format-Table -AutoSize
    return
}

# 4. Purge Messages in Chunks of 20 via Graph $batch Endpoint
$BatchSize = 20
$TotalDeleted = 0

for ($i = 0; $i -lt $Messages.Count; $i += $BatchSize) {
    $Chunk = $Messages[$i..([Math]::Min($i + $BatchSize  1, $Messages.Count  1))]
    $Requests = [System.Collections.Generic.List[object]]::new()
    $ReqId = 1

    foreach ($Msg in $Chunk) {
        $Requests.Add(@{
            id     = "$ReqId"
            method = "POST"
            url    = "/users/$Mailbox/messages/$($Msg.id)/permanentDelete"
        })
        $ReqId++
    }

    $BatchBody = @{ requests = $Requests } | ConvertTo-Json -Depth 4
    $BatchResp = Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/`$batch" -Body $BatchBody
    $TotalDeleted += $Chunk.Count
    Write-Host "[+] Purged $TotalDeleted / $($Messages.Count) messages..." -ForegroundColor Green
}

Write-Host "[✔] Successfully emptied $TotalDeleted messages from '$FolderPath' in $Mailbox!" -ForegroundColor Green

Method 2: On-Premises Exchange Server — EWS Recursive Folder Path Script

For on-premises Exchange Server 2016, 2019, and Exchange SE, the EWS script below resolves any folder path (\Deleted Items or \Inbox\Subfolder) using the Get-EwsFolderByPath helper function and deletes all items inside it:

POWERSHELL
########################################
# Script Name : Delete_ALL_MSG_EWS-specific-folder.ps1
# Author      : Sunil Chauhan (LAB 365 - https://www.lab365.in)
# Purpose     : Deletes all emails from a specific folder path in a mailbox via EWS Managed API 2.0
########################################

param (
    [string]$User       = "[email protected]",
    [string]$Pass       = "Password",
    [string]$Mailbox    = "[email protected]",
    [string]$FolderPath = "\Deleted Items",
    [string]$EwsUrl     = "https://mail.lab365.in/EWS/Exchange.asmx",
    [switch]$UseFastFolderEmpty
)

# 1. Load EWS Managed API 2.0 DLL
$EWSServicePath = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
Import-Module $EWSServicePath

$Service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1)
$Service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($User, $Pass)
$Service.Url = [uri]$EwsUrl

# Configure Impersonation if acting on another user's mailbox
$Service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId(
    [Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,
    $Mailbox
)

$MailboxRootId = New-Object Microsoft.Exchange.WebServices.Data.FolderId(
    [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,
    $Mailbox
)
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($Service, $MailboxRootId)

# 2. Helper Function: Resolve Folder Object from Path (e.g., "\Inbox\ProjectA")
function Get-EwsFolderByPath {
    param (
        [Microsoft.Exchange.WebServices.Data.Folder]$RootFolder,
        [string]$Path
    )
    $Current = $RootFolder
    if ($Path -ne '\') {
        $PathElements = $Path.Trim('\') -split '\\'
        foreach ($Element in $PathElements) {
            if ($Element) {
                $View = New-Object Microsoft.Exchange.WebServices.Data.FolderView(2, 0)
                $View.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Shallow
                $View.PropertySet = [Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly
                $SearchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo(
                    [Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,
                    $Element
                )
                $FolderResults = $Current.FindFolders($SearchFilter, $View)
                if ($FolderResults.TotalCount -ne 1) {
                    Write-Warning "Failed to uniquely resolve folder '$Element' in path '$Path'"
                    return $null
                }
                $Current = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($Service, $FolderResults.Folders[0].Id)
            }
        }
    }
    return $Current
}

try {
    $FolderObject = Get-EwsFolderByPath -RootFolder $MailboxRoot -Path $FolderPath
    if (-not $FolderObject) { return }

    if ($UseFastFolderEmpty) {
        # Instant server-side folder empty (HardDelete all items, preserve subfolders = $false)
        $FolderObject.Empty([Microsoft.Exchange.WebServices.Data.DeleteMode]::HardDelete, $false)
        Write-Host "[✔] Emptied folder '$FolderPath' via server-side Folder.Empty()." -ForegroundColor Green
    } else {
        # Paged item-by-item loop (up to 1,000 items per page)
        $ItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)
        $Deleted = 0
        do {
            $FindItemResults = $FolderObject.FindItems($ItemView)
            foreach ($Item in $FindItemResults.Items) {
                try {
                    [void]$Item.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::HardDelete)
                    $Deleted++
                } catch {
                    Write-Warning "Unable to delete item '$($Item.Subject)': $($_.Exception.Message)"
                }
            }
        } while ($FindItemResults.MoreAvailable)

        Write-Host "[✔] $Deleted mail items hard-deleted from '$FolderPath'." -ForegroundColor Green
    }
} catch {
    Write-Warning "Error accessing folder '$FolderPath': $($_.Exception.Message)"
}