PowerShell 7.2.7 and Could not load type ‘System.Security.Cryptography.SHA256Cng’

The error is described in the title but what leads to this error?

Generating the problem with Connect-AzureAD module

When you have PowerShell 7.* installed and you want to install Azure AD module and connect to Azure AD, the install goes OK.

Then you the module with import-module AzureAD, all ok.

Then you connect to Azure AD and it will ask for credentials.

Once you authenticate, you get the error.

Fixing the problem

Try UseWindowsPowerShell switch

If you run import-module command with -UserWindowsPowerShell switch

Which is documented here.

You will receive the following error.

Why this happens?

The -UserWindowsPowerShell switch will initate an Remote Session to the old PowerShell 5.* and will run the command from it’s context.

How to fix?

Open your PowerShell 5.* and install and import the Azure AD module.

Let’s try again

Run the command again and success!

What you will see in the end

You will find the session inside your PowerShell 7.* session

What is WinPSCompatSession?

PowerShell generates a remote session called WinPSCompatSession that is running in the background as a Windows PowerShell 5.1 process when the first module is imported utilizing the Windows PowerShell Compatibility feature.

Through implicit remoting, the modules loaded in the WinPSCompatSession session are used and mirrored into the active PowerShell session. The transport method used for PowerShell jobs is the same as this one.

How it works?

When we open PowerShell, we have one PowerShell Core Runspace

And once we import the module with WinPSCompatSession there will be two.

Even though it looks like traditional PS Remoting sessions, it isn’t.

Why it happens?

Azure AD cmdlets aren’t supported in PowerShell 7.* but the method described above works over this limitation.

Although I highly recommend using Microsoft Graph from now on. When you will get a hang of it, you will find that is more consistent and has more possibilities than PowerShell itself had.

Graph

First you have to install and import the Graph modules.

Then connect to Graph API with the permissions you need and consent to them.

And in the consent you will “Read all”

When doing a Read and Write permissions.

You will see “Read and write” in the consent screen

Closure

“Legacy” things still work but you really should upgrade to Graph. Microsoft has an excellent guide just for this. All the old cmdlets aren’t yet supported but it’s getting there.

And here a list of the corresponding Graph commands compared to old style Azure AD PowerShell cmdlets

If you have scripts that need checking, there is also this tool available.

Author: Harri Jaakkonen

Leave a Reply

Your email address will not be published. Required fields are marked *