Skip to content

How to connect to Microsoft Graph PowerShell

There are different methods to connect to Microsoft Graph PowerShell to manage your Microsoft 365 and Azure tenant. Which one of the methods suits you depends on what you want. A good example is to connect to Microsoft Graph PowerShell to automate Microsoft Graph PowerShell scripts without user interaction. In this article, you will learn how to connect to Microsoft Graph PowerShell with three different methods.

Prerequisites

You need to Install the Microsoft Graph PowerShell modules on your system.

Start Windows PowerShell as administrator and run the below commands.

Install-Module Microsoft.Graph -Force
Install-Module Microsoft.Graph.Beta -AllowClobber -Force

Important: Always install the Microsoft Graph PowerShell and Microsoft Graph Beta PowerShell modules. That’s because some cmdlets are not yet available in the final version, and they will not work. Update both modules to the latest version before you run a cmdlet or script to prevent errors and incorrect results.

Method 1 – How to connect to Microsoft Graph with user interaction

The first method is the method that you will use most of the time because you want to connect to Microsoft Graph with your account and use the commands.

Connect-MgGraph -Scopes "User.Read.All"

Verify with your credentials, and you will return to the PowerShell window.

Method 2 – How to connect to Microsoft Graph with Certificate Based Authentication CBA

The second method is to register an application in Azure with the permissions. Let’s go through the below steps and set up Microsoft Graph Certificate Based Authentication for unattended scripts.

1. Register application in Azure

To register an application in Azure AD, follow these steps:

  1. Sign in to Microsoft Entra admin center
  2. Expand Azure Active Directory
  3. Click on Applications > App registrations
  4. Select New registration
New app registration
  1. Fill in the name MSGraph-Automation
  2. Select Accounts in any organizational directory (Any Azure AD directory – Multitenant) and personal Microsoft accounts
  3. Click Register
Register application
  1. The MSGraph-Automation application Overview appears
  2. Copy the Application (client ID) and Directory (tenant) ID and paste it into Notepad because you will need it later when connecting to Microsoft Graph
Connect to Microsoft Graph PowerShell Application (client) ID and Directory (tenant) ID

2. Configure Azure application API permissions

You need to add API permissions to the MSGraph-Automation application you created, by following the below steps:

  1. Click on API permissions > Add a permission
Connect to Microsoft Graph PowerShell add API permissions
  1. Select Microsoft APIs > Microsoft Graph
Request API permissions
  1. Select Application permissions
  2. Search for user.read.all
  3. Expand User and select User.Read.All
  4. Click Add permissions
Connect to Microsoft Graph PowerShell select application permissions
  1. Click on Grant admin consent
  2. Click Yes
Connect to Microsoft Graph PowerShell Grant admin consent
  1. The status shows a green checkmark
API permissions granted

Now that the application is registered and the API permissions are set, we can configure two methods for authentication; Certificate or Client Secret.

3. Generate self-signed certificate

To generate a self-signed certificate, log onto any Windows Server or Desktop with Windows PowerShell. It’s best to generate the certificate on the machine you want to run the unattended PowerShell script.

You need the self-signed certificate later in the steps when you upload it to the application in Azure and if you want to use the certificate on other systems.

Note: By default, self-signed certificates are valid for one year.

In this case, we added 5 years to the self-signed certificate, so we don’t have to renew it yearly.

$mycert = New-SelfSignedCertificate -DnsName "exoip.com" -CertStoreLocation "cert:\LocalMachine\My" -NotAfter (Get-Date).AddYears(5) -KeySpec KeyExchange -FriendlyName "MSGraph Automation"

Confirm the certificate and copy the ThumbPrint and paste it into Notepad. You will need it later when connecting to Microsoft Graph.

$mycert | Select-Object -Property Subject,Thumbprint,NotBefore,NotAfter

This is what the output looks like.

Subject      Thumbprint                               NotBefore           NotAfter           
-------      ----------                               ---------           --------           
CN=exoip.com 384010504F6B495B6D53B1C55DC6C1A7273081AC 7/7/2023 6:14:36 PM 7/7/2028 6:24:36 PM

Export certificate to .cer file.

You will need that .cer file when you upload it to the Azure application, which you will create in the next steps.

$mycert | Export-Certificate -FilePath "C:\temp\MSGraphAutomationCert.cer"

The output appears.

    Directory: C:\temp


Mode                LastWriteTime         Length Name                     
----                -------------         ------ ----                     
-a----         7/7/2023   6:25 PM            796 MSGraphAutomationCert.cer

Export certificate to .pfx file.

You will need that .pfx file when using another machine to connect with Certificate Based Authentication. Copy or send the .pfx file and install it on other machines.

$mycert | Export-PfxCertificate -FilePath "C:\temp\MSGraphAutomationCert.pfx" -Password $(ConvertTo-SecureString -String "P@ssw0Rd1234" -AsPlainText -Force)

The output appears.

    Directory: C:\temp


Mode                LastWriteTime         Length Name                     
----                -------------         ------ ----                     
-a----         7/7/2023   6:26 PM           2717 MSGraphAutomationCert.pfx

4. Upload certificate to application

You need to upload the self-signed certificate you created in the previous step:

  1. Click on Certificates & secrets
  2. Click Certificates > Upload certificate
  3. Click on the browse icon and select the self-signed MSGraphAutomationCert.cer file in C:\temp
  4. Add the description MS Graph Automation Cert
  5. Click Add
Connect to Microsoft Graph PowerShell upload certificate
  1. The certificate appears in the list

Note: Confirm that it has the same certificate thumbprint as the one you exported in the previous step.

Connect to Microsoft Graph PowerShell Thumbprint value

5. Connect to Microsoft Graph with Certificate Based Authentication

Start Windows PowerShell ISE or Visual Studio Code and fill in the below three variables to connect to Microsoft Graph PowerShell with Certificate Based Authentication:

  1. $ClientId
  2. $TenantId
  3. $CertificateThumbPrint
# Configuration
$ClientId = "0a613e88-a189-4eac-b8c3-055196fd04d6"
$TenantId = "eb403171-a4ec-4d98-a08f-1876318c9deb"
$CertificateThumbprint = "384010504F6B495B6D53B1C55DC6C1A7273081AC"

# Connect to Microsoft Graph with CBA
Connect-MgGraph -ClientId $ClientId -TenantId $TenantId -CertificateThumbprint $CertificateThumbprint

Now that you are connected to Microsoft Graph PowerShell, run the Get-MgUser cmdlet to retrieve the users.

Get-MgUser

Method 3 – How to connect to Microsoft Graph with Client Secret

The third method is to register an application in Azure with the permissions. Let’s go through the below steps and set up Microsoft Graph Client Secret for unattended scripts.

1. Register an application in Azure

Go through the above step to register an application in Azure if you didn’t do this.

2. Configure Azure application API permissions

Go through the above step to configure Azure application API permissions if you didn’t do this.

3. Add a Client Secret

You need to add a Client Secret that the application uses to prove its identity when requesting a token.

  1. Click on Certificates & secrets
  2. Click Client secrets > New client secret
  3. Give it the description MS Graph Automation Secret
  4. Select the expires date 730 days (24 months)
  5. Click Add
Connect to Microsoft Graph PowerShell add Client Secret
  1. Copy the Client Secret Value and paste it into Notepad because you will need it in the next step when connecting to Microsoft Graph
Connect to Microsoft Graph PowerShell Client Secret value

4. Connect to Microsoft Graph with Client Secret

Start Windows PowerShell ISE or Visual Studio Code and fill in the below three variables to connect to Microsoft Graph PowerShell with Client Secret:

  1. $ClientId
  2. $TenantId
  3. $ClientSecret
# Configuration
$ClientId = "0a613e88-a189-4eac-b8c3-055196fd04d6"
$TenantId = "eb403171-a4ec-4d98-a08f-1876318c9deb"
$ClientSecret = "Kos8Q~nVLcjmmyGSY68qDg4zbdF8f51L2EM50ac5"

# Convert the client secret to a secure string
$ClientSecretPass = ConvertTo-SecureString -String $ClientSecret -AsPlainText -Force

# Create a credential object using the client ID and secure string
$ClientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ClientId, $ClientSecretPass

# Connect to Microsoft Graph with Client Secret
Connect-MgGraph -TenantId $tenantId -ClientSecretCredential $ClientSecretCredential

Now that you are connected to Microsoft Graph PowerShell, run the Get-MgUser cmdlet to retrieve the users.

Get-MgUser

That’s it!

Read more: Renew Client Secret in Microsoft Entra ID »

Conclusion

You learned how to connect to Microsoft Graph PowerShell with three methods. Go through the step-by-step guide, and you can authenticate with Microsoft Graph PowerShell with user interaction (method 1) or without user interaction for unattended scripts (method 2/3). All these methods are excellent to work with.

Did you enjoy this article? You may also like Create Microsoft Entra ID Users from CSV with PowerShell. Don’t forget to follow us and share this article.

ALI TAJRAN

ALI TAJRAN

ALI TAJRAN is a passionate IT Architect, IT Consultant, and Microsoft Certified Trainer. He started Information Technology at a very young age, and his goal is to teach and inspire others. Read more »

This Post Has 0 Comments

Leave a Reply

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