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
}