ExchangeOnlineManagement progressively consumes more memory

Aaron Hodgins 25 Reputation points
2026-09-01T07:03:08.26+00:00

I'm experiencing memory leaks using the Get-EXOMailboxFolderPermission commandlet.

The Get-EXOMailboxFolderPermission and likely other commandlets that extend the AdminCmdlet which registers a ConsoleCancelEventHandler but doesn't clean it up. So repeatedly calling this commandlet continues to increase RAM usage in the process.

# Snippet of AdminCmdlet::BeginProcessing	
Console.CancelKeyPress += delegate
	{

		CancellationTokenSource.Cancel();

	};

Using reflection to find and remove via [System.Console]::remove_CancelKeyPress($handler) fixes it.

# Example function to call after invoking Get-EXOMailboxFolderPermission to clear the handlers
Function Clear-ExoCancelKeyPressHandlers {
    $flags = [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Static
    $field = [System.Console].GetFields($flags) |
            Where-Object { $_.FieldType -eq [System.ConsoleCancelEventHandler] } |
            Select-Object -First 1

    if ($null -eq $field) {
        return 0
    }

    $current = $field.GetValue($null)
    if ($null -eq $current) { return 0 }
    $removed = 0

    foreach ($handler in $current.GetInvocationList()) {
        $target = $handler.Target
        if ($null -eq $target) {continue }
        $type  = $target.GetType()
        $isExo = $false
        while ($null -ne $type) {
            if ($type.FullName -like 'Microsoft.Exchange.Management.RestApiClient.AdminCmdlet*') {
                $isExo = $true
                break
            }
            $type = $type.BaseType
        }
        if ($isExo) {
            [System.Console]::remove_CancelKeyPress($handler)
            $removed++
        }
    }

    return $removed
}
Exchange Online
Exchange Online

A cloud-based service included in Microsoft 365, delivering scalable messaging and collaboration features with simplified management and automatic updates.

0 comments No comments

Answer accepted by question author
Vasil Michev 127.8K Reputation points MVP Volunteer Moderator
2026-09-01T07:12:14.0766667+00:00

Thanks for reporting this, I will forward it to the ExO PowerShell team.

As a side note, you can bypass the module altogether and use the underlying REST endpoints (for any -EXO* cmdlet) or the InvokeCommand method (for any "old" cmdlet), thus alleviating any similar issues. I have a writeup on this here: https://michev.info/blog/post/5822/all-you-need-to-know-about-exchange-online-admin-api-or-how-to-run-cmdlets-without-powershell

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Oldest

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.