Connect-MgGraph Fails with a Token Cache TypeLoadException After Module Update
Asked by
PAPERBACK SWAP
Several PowerShell 5.1 scripts manage users, mail, distribution groups, and account notifications through Exchange Online and Microsoft Graph. They worked reliably until recently, but now Connect-MgGraph fails with a TypeLoadException stating that RefreshCacheAsync in InMemoryTokenCacheOptions from Microsoft.Graph.Authentication.Core version 2.40.0.0 has no implementation. Send-MgUserMail then fails because authentication never completed. The app registrations, certificates, tenant and client IDs, and service account all appear valid. The scripts load both Exchange-related modules and Microsoft Graph modules, currently version 2.40.0, on Windows PowerShell 5.1. Has anyone found a fix or workaround for this module compatibility issue?
Answers
You can roll back the affected modules with something like: Install-Module -RequiredVersion 2.39.0 Microsoft.Graph.Authentication,Microsoft.Graph.Mail, then use Import-Module -RequiredVersion 2.39.0 for both modules. Make sure the older versions are actually installed and selected, since PowerShell may otherwise load 2.40.0 from the module path.
Reply to this answer
If downgrading does not solve it, test Connect-MgGraph in a clean PowerShell session and compare that with the full script. If it works by itself, another loaded administration module is probably causing the assembly conflict. Separating the Graph and Exchange operations into different scripts or processes can avoid the conflicting assemblies.
Reply to this answer
This looks like a compatibility problem introduced by the 2.40.0 Graph update rather than an issue with the app registration or credentials. Graph authentication and Exchange modules can load conflicting dependency versions in the same PowerShell process. Try pinning the Graph authentication and mail modules to 2.39.0 and explicitly importing those versions before connecting.
Reply to this answer
Version 2.40.0 had only recently been released when this started, so check its release notes and known issues. As a temporary fallback, the mail request could be sent directly through the Graph REST endpoint with Invoke-RestMethod, which avoids the SDKโs token-cache assembly dependency, although authentication still needs to be implemented correctly.
Reply to this answer
Add your answer
Answers are reviewed before publication.
PAPERBACK SWAP: The scripts also load the Exchange modules, so that may explain the conflict. Iโm going to test the previous Graph version and pin the imports.