Move scripts from Azure AD modules to Microsoft Graph Modules

Page content

In the last few weeks, I took some time to refactor most of my scripts and Azure Automation script to use the Microsoft Graph Modules over the Azure AD Module. As I explained in my previous blog, the Azure AD module is declared deprecated.

How to start updating

The first thing to do of course is to install the latest Microsoft Graph Modules with:

Install-Module Microsoft.Graph

Connecting to the Graph

Connecting to the Microsoft Graph is almost the same as via Azure AD, except there are a few extra options

Connect-AzureAD

With Azure AD, this is pretty straightforward, the above will open a browser window to log in, and you’re done. With the Graph, this is slightly different. If you are connecting the first time, you need to add the Scopes that are needed for what you are about to do. After that, these scopes are not needed as they are already set unless you need more permissions.

# Connecting the first time
Connect-MgGraph -Scopes "User.Read.All", "Group.ReadWrite.All"

# Connecting after that
Connect-MgGraph

Finding the required scopes

Unlike the AzureAD module, you have seen that a scope is needed. The AzureAD modules will give you access to what directory role you have as the Graph modules need to be configured in the Azure AD Application, and you can only add the scopes that your directory role has access to. With the Find-MgGraphCommand you can see what scopes are needed to run the particular command, this can be more than one, but only one of them is needed

Find-MgGraphCommand -command Get-MgUser | Select -First 1 -ExpandProperty Permissions

Checking the scopes of your connection

To find out what scopes you have access to, run the following command

(Get-MgContext).Scopes

Finding the correct commands

The way Microsoft Graph is structured is different from the Azure AD module; this is because the modules are generated directly from the Graph API. Therefore Microsoft has created an overview of most of the Azure AD commands and the Graph Command. https://learn.microsoft.com/en-us/powershell/microsoftgraph/azuread-msoline-cmdlet-map?view=graph-powershell-1.0

Using the Graph Versioning

The Microsoft Graph has currently two versions, the V1 and the beta Version; by default, you connect to the V1 version. This is the stable version but does not have everything or every detail in it, and therefore, you need the beta API sometimes. This can be done by changing the profile

Select-MgProfile -Name "beta"

But be aware that in Microsoft.Graph V2 modules this is going to change, and you need a differnt set of Graph modules, but until then, the Select-MgProfile will work

References