Office 365: Release Messages from Quarantine using PowerShell

Modified on Mon, 20 Apr at 6:48 PM

$DomainFilter = "@mydomain\.com$"
$totalPages = 10
$pageSize = 1000

Connect-ExchangeOnline

Write-Host "Fetching up to $($totalPages * $pageSize) pending quarantine messages across $totalPages pages..." -ForegroundColor Cyan

# Efficiently gather multiple pages of results
$allQuarantinedMessages = foreach ($page in 1..$totalPages) {
    Write-Host "Fetching page $page..." -ForegroundColor DarkCyan
    
    $pageResults = Get-QuarantineMessage -PageSize $pageSize -Page $page
    
    # If a page returns nothing, we've hit the end of the queue. Break the loop early.
    if (-not $pageResults) {
        Write-Host "Reached the end of the queue before page $totalPages." -ForegroundColor DarkGray
        break
    }
    
    # Output the results to the $allQuarantinedMessages collection
    $pageResults
}

# Filter the combined results for internal-to-internal routing waiting for review
$filteredMessages = $allQuarantinedMessages | Where-Object {
    $_.SenderAddress -match $DomainFilter -and 
    $_.RecipientAddress -match $DomainFilter -and
    $_.ReleaseStatus -eq "NotReleased"
}

if ($filteredMessages) {
    
    # Pipe the filtered results to an interactive grid view for selection
    $selectedMessages = $filteredMessages | 
        Select-Object ReceivedTime, SenderAddress, RecipientAddress, Subject, ReleaseStatus, Identity | 
        Out-GridView -Title "Select Pending Messages to Release (Hold CTRL to select multiple)" -PassThru
    
    # Process the selected messages
    if ($selectedMessages) {
        
        # Filter down to distinct IDs to avoid duplicate release attempts on CC'd messages
        $uniqueMessages = $selectedMessages | Sort-Object Identity -Unique

        foreach ($msg in $uniqueMessages) {
            Write-Host "Releasing message: '$($msg.Subject)' (Message ID: $($msg.Identity))" -ForegroundColor Yellow
            
            # Release the message to all originally intended recipients
            Release-QuarantineMessage -Identity $msg.Identity -ReleaseToAll
        }
        Write-Host "Release process complete." -ForegroundColor Green
    } else {
        Write-Host "No messages were selected. Exiting." -ForegroundColor DarkGray
    }

} else {
    Write-Host "No pending quarantined messages found matching the @levian.com criteria in the first $totalPages pages." -ForegroundColor Red
}

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article