Connecting to Exchange Online with Connect-ExchangeOnline is slow within Azure Function

Connecting to Exchange Online with Connect-ExchangeOnline is slow within Azure Function
Photo by Nick Abrams / Unsplash

I've written previously about building an Azure Function that connects with Exchange Online. One of the reasons for this was the need to modify a given user's proxyaddresses property.

One issue I've persistently hit is with Connect-ExchangeOnline. Running this via managed identity with the following syntax:

Connect-ExchangeOnline -ManagedIdentity -Organization $tenant

This would take up to 35 seconds to complete! The other issue was excess memory usage. Each call to an Azure Function consumed 300-500 MB of memory of the App Plan compute instance. After 3 or 4 calls, it would simply run out of memory. Remove-PSSession didn't seem to clean up the Exchange Online session.

To fix this, the slow connect time can be mitigated by adding the CommandName parameter for Connect-ExchangeOnline. You'll need to introduce only the cmdlets you plan on using, and this in turn, reduces the memory footprint and improves performance. See details here. The connection now happens with:

Connect-ExchangeOnline -ManagedIdentity -Organization $tenant -CommandName Set-Mailbox,Disconnect-ExchangeOnline

The other issue for excess memory usage has to do with a memory leak in Connect-ExchangeOnline. To clear up the session objects, use Disconnect-ExchangeOnline -Confirm:$false before Remove-PSSession. In addition, enforce garbage collection with [System.GC]::Collect().

With these changes, the Azure Function completes in 4 seconds (down from about 35-40 seconds), and the memory footprint stays under 300MB at all times.

I hope this helps anyone else struggling with slow Connect-ExchangeOnline issues!