Skip to content

Microsoft Graph & PowerShell SDK

Connecting to the Graph SDK

The first step in any use of the Graph SDK is to connect to the Graph using the Connect-MgGraph cmdlet. When you run Connect-MgGraph to connect to the Graph, it’s wise to specify the identifier of the tenant to which you want to connect.

Connect-MgGraph -TenantId “828e1143-88e3-492b-bf82-24c4a47ada63”

If you don’t specify a tenant, Connect-MgGraph will choose the last tenant you signed into during a session (which might not be the one you want to connect to). I discovered this when I connected to the Graph and discovered that the data used belonged to my development tenant. I noticed then, but it’s possible that someone might miss this elsewhere, so make it a habit to connect with the tenant identifier.

A session lasts until you run Disconnect-MgGraph (see below) and can be reinitiated multiple times over days by running Connect-MgGraph. Behind the scenes, the Graph SDK keeps an encrypted token cache and will refresh the token as needed to allow you to work with Graph commands.

Gathering New Permissions

As people begin executing Graph SDK commands using the interactive client, they will need consent for the permissions needed to run the commands. For example, to use the Get-MgUser cmdlet to retrieve a set of Azure AD accounts, a user needs permission to read directory information, so they might request the permissions using the Scope parameter when making the connect as follows:

$RequiredScopes = @(“Directory.AccessAsUser.All”, “Directory.ReadWrite.All”)

Connect-MgGraph -Scopes $RequiredScopes

Reporting Your Connection

To check that you’re connected to the right tenant with the right profile and permissions, we can extract information about the tenant with the Get-MgOrganization cmdlet, the current connection with the Get-MgContext cmdlet, and the profile used with the Get-MgProfile cmdlet and display some useful information:

$Details = Get-MgContext

$Scopes = $Details | Select -ExpandProperty Scopes

$Scopes = $Scopes -Join “, “

$OrgName = (Get-MgOrganization).DisplayName

CLS

Write-Host “Microsoft Graph Connection Information”

Write-Host “————————————–“

Write-Host ” “

Write-Host (“Connected to Tenant {0} ({1}) as account {2}” -f $Details.TenantId, $OrgName, $Details.Account)

Write-Host “+——————————————————————————————————————-+”

Write-Host (“Profile set as {0}. The following permission scope is defined: {1}” -f $ProfileName, $Scopes)

Write-Host “”

Disconnect When You’re Done

When you’re finished interacting with the Graph, remember to close off the session by running Disconnect-MgGraph to sign the session out from the Graph. Disconnecting the session removes the encrypted token cache and prevents a session from being reinitialized.

Disconnect-MgGraph

Posted from: https://practical365.com/connect-microsoft-graph-powershell-sdk/

Leave a Reply

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