Learning and Sharing
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
No Result
View All Result

How to Connect to Microsoft Graph PowerShell API

October 20, 2023
in Blog, Microsoft Graph, Powershell
0
ADVERTISEMENT

Table of Contents

After you install the Microsoft Graph module, you can connect to Microsoft Graph PowerShell. There are different methods to connect to Microsoft Graph PowerShell. In this article, we will show you how to connect to Microsoft Graph with interactive mode, self-signed certificate, and client secret.

Azure Active Directory Graph API

The Azure Active Directory Graph API has been deprecated since June 30, 2023, so now you must migrate your apps to Microsoft Graph. Once you connect to Microsoft Graph, you can access Entra ID services and Microsoft 365 services.

Microsoft Graph has all the capabilities available in Entra ID Graph and new APIs like identity protection and authentication methods.

Install Microsoft Graph PowerShell module

1️⃣ First, you need to install the Microsoft Graph PowerShell module. We recommend you update to the latest version, because some of the cmdlets will not work.

Note Note: You need to install Microsoft Graph PowerShell module v2.x to connect with Microsoft Graph to run automated scripts.

2️⃣ Or you can open Windows PowerShell as administrator then run all below commands at once to download and install all required packages and modules.

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force
Install-PackageProvider -Name NuGet -Force
Install-Module PowerShellGet -Force
Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted
Install-Module Microsoft.Graph -Force
Install-Module Microsoft.Graph.Beta -Force

3️⃣ Once done, you can verify you have installed the Microsoft Graph PowerShell module and see which version is running using the below PowerShell cmdlet.

Get-InstalledModule | ? {($_.Name -eq 'Microsoft.Graph') -or ($_.Name -eq 'Microsoft.Graph.Beta')}

Version Name                 Repository Description
------- ----                 ---------- -----------
2.6.1   Microsoft.Graph      PSGallery  Microsoft Graph PowerShell module
2.6.1   Microsoft.Graph.Beta PSGallery  Microsoft Graph PowerShell module

Bonus: You can always keep your PowerShell modules up to date and run the below command.

Update-Module Microsoft.Graph

After you installed the Microsoft Graph PowerShell module, you can start to connect.

Methods to connect to Microsoft Graph PowerShell

We will show you three methods to connect to Microsoft Graph PowerShell:

  1. Interactive mode (delegated access)
  2. Certificate Based Authentication (CBA)
  3. Client secret (password)

The first method is the easiest as you only need to connect with PowerShell. The other two methods are similar because it requires creating a new application in Entra ID. The difference between method 2 and 3 is that there are two ways to authenticate your newly created application in Azure Active Directory.

We will show you both ways but recommend to add a certificate (CBA) rather than a client secret for your application because they are not as secure.

Method 1: Connect MgGraph with interactive mode

The first method is the quickest and easiest way to connect to Microsoft Graph API with PowerShell.

1️⃣ Open PowerShell as administrator and run the below command.

Connect-MgGraph

2️⃣ Sign in with your admin credentials.

  • Enter your admin account and password.
  • Click Sign in.
bgfQhYACkpx9lnO7Isr7VMXrFbySu7pbAiL9tFTeCqXgj3cDtzlaMDJlJ4MC

3️⃣ If you have MFA enabled, you will get a verification code sent as a text message or to your Authentication app on your phone. If your MFA is disabled, you will not do anything here.

4️⃣ Now you must go back to the PowerShell windows, where you get this below output.

PS C:\> Connect-MgGraph
Welcome To Microsoft Graph!
PS C:\> Get-MgContext

ClientId               : 14d82eec-204b-4c2f-b7e8-296a70dab67e
TenantId               : c032627b-6715-4e39-9990-bcf48ee5e0c5
Scopes                 : {Group.ReadWrite.All, openid, profile, User.ReadWrite.All...}
AuthType               : Delegated
TokenCredentialType    : InteractiveBrowser
CertificateThumbprint  :
CertificateSubjectName :
Account                : [email protected]
AppName                : Microsoft Graph Command Line Tools
ContextScope           : CurrentUser
Certificate            :
PSHostVersion          : 5.1.19041.3031
ManagedIdentityId      :
ClientSecret           :
Environment            : Global
Note Note: You can’t run automated scripts, but it is usable for testing or to run a script. If you like to run an automated task, you should use the next method.

Method 2: Connect with Certificate Based Authentication

Before we can connect to Microsoft Graph with PowerShell, you need to:

  • Register an application in Entra ID and assign API permissions.
  • Then create a self-signed certificate to the application.

Register new application in Entra ID

First, you need to register an application, where you will get the Application (client) ID and Directory (tenant) ID. Register a new application in Microsoft Entra admin center:

1️⃣ Sign into Microsoft Entra admin center > Identity > Applications > App registrations > New registration.

9UaxOZCEfibAXwhY0esxzhY6sx1FswCdsSJeyVNqIJu6ydcSpmLWTIr8gq2m

2️⃣ Register an application.

  • Name your application as you want.
  • Select Accounts in this organizational directory only (- Single tenant)
  • Click Register
ZIiMU3miJfEup8JZL6oIbTQXLK7aPr4MRwCRgyyoDAFp9T6ttRs4orBOMxAM

3️⃣ Successfully created application, you will be redirected to the app overview page. Copy the Application ID and Directory ID.

gMUdOWUaKr9INpAfU49hzPBGElOD7Q4MYczuZIgSlLTbhtvRWm9PzgpuxtN2

You need to copy the below values and paste them into Notepad because you need them later when connecting to Microsoft Graph:

  • Application (client) ID: 3c17a3d6-8f7f-4407-b76f-ff0d22e4ab7a
  • Directory (tenant) ID: c032627b-6715-4e39-9990-bcf48ee5e0c5

Assign API permissions

You must assign API permissions to the application you created.

1️⃣ Click API permission > Click Add a permission

FDhKHyuGRDdcsTbZvXC9HfMPUaJQftHrjdwUaWrHi4JavH6fy67AOGLXspOQ

2️⃣ Under the tab Microsoft APIs > Click Microsoft Graph

Mke4fsR67hQUxa83fCiTDiXHrOttKMepXhNS5PICaoLmWj4e1P9q3MSeTE5e

3️⃣ Click Application permissions > Search for User.Read.All > Select User > User.Read.All > Click Add permissions

7mp4lsWY3jpZLNVLuIdvabio88pUTrSo1qktS3NSHWDCX2WagEiq7WOYgqNU

4️⃣ Click Grant admin consent for your tenant > Click Yes

bDvSkFdcs77WOiPezBsGGxfwzkF3yXXaWn4aWazWW2Oc0OGCkVuF2oSLQWT1

A green check mark appears that you granted admin consent successfully!

AC6ZIygIjr7Avyk0C9qfsWGyocCCuWUa3RGx9oykTLDQP5vyrKWZPCNLS3lw

Create self-signed certificate

Once you created a new application, you can use a self-signed certificate to upload a .pfx file and .cer file to Entra ID.

First, you need to generate a self-signed certificate. It’s better to make the certificate on the same machine you want to run the unattended PowerShell script.

1️⃣ Log into any Windows Server or Desktop with Windows PowerShell as administrator.

Note Note: Self-signed certificate is valid for one year by default. In our example, we will add 5 years to the self-signed certificate to avoid yearly renewal.

2️⃣ Use the below PowerShell cmdlet to create a new self-signed certificate.

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

3️⃣ The certificate is now stored, to view the thumbprint, use the below PowerShell cmdlet.

PS C:\> $mycert | Select-Object -Property Subject,Thumbprint,NotBefore,NotAfter

Subject          Thumbprint                               NotBefore             NotAfter
-------          ----------                               ---------             --------
CN=bonguides.com 4619B79D13DF75AC5A207C0692FAA2AF537007EF 8/20/2023 11:16:10 PM 8/20/2028 11:26:10 PM

4️⃣ Copy the Thumbprint and paste it into Notepad. You will need it later when you connect to Microsoft Graph PowerShell with CBA.

PS C:\> ($mycert).Thumbprint
4619B79D13DF75AC5A207C0692FAA2AF537007EF

Export to .cer file with PowerShell

We want to create a .cer file to upload later in Entra ID application. With a .cer file you can only connect to Microsoft Graph from the machine where the self-signed certificate is generated.

1️⃣ Create a folder named temp to save it in the C:\temp.

2️⃣ Use the below PowerShell cmdlet to export the certificate to .cer file.

New-Item -Path C:\temp -Type Directory
$mycert | Export-Certificate -FilePath "C:\temp\myauth.cer"

You will see the below output in PowerShell. You can find the .cer file on your computer in C:\temp.

PS C:\> $mycert | Export-Certificate -FilePath "C:\temp\myauth.cer"

    Directory: C:\temp

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         8/20/2023  11:33 PM            808 myauth.cer

Export to .pfx file

We will also create a .pfx file so that you can connect to Microsoft Graph from any machine. You can copy or send a .pfx file to a person so it can be installed on another machine, because the .pfx file will be retrieved during the authentication process.

$mycert | Export-PfxCertificate `
    -FilePath "C:\temp\myauth.pfx" `
    -Password $(ConvertTo-SecureString -String "123456" -AsPlainText -Force)

You can find the .pfx file on your computer in C:\temp.

PS C:\> ls C:\temp\

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         8/20/2023  11:33 PM            808 myauth.cer
-a----         8/20/2023  11:36 PM           2693 myauth.pfx

Upload certificate to app

Now we need to upload the self-signed certificate you created earlier.

From the app overview:

  1. Click Certificates & secrets
  2. Select Certificates
  3. Click Upload certificate
  4. Click on the browse icon to search in C:\temp and select the myauth.cer file
  5. Add description
  6. Click Add
4MqChKUY24qmPGhvh4KUEqYg4y5G8MUQfMRvvbbT8ipW0pDltjfTqa2GSMQ4

The certificate appears in the list with the thumbprint. Always ensure it has the same certificate thumbprint as the one you created previously.

qzj9QMMx9K7scyqThqBM4jv6mieJMN2wFrH7EXJxLoGoiBhlbPkciGwIsWBW

Connect to Microsoft Graph with CBA

Type the below information to connect to Microsoft Graph PowerShell with Certificate Based Authentication.

Run the below PowerShell script to connect to Microsoft Graph with CBA.

# Configuration
$ClientId = "3c17a3d6-8f7f-4407-b76f-ff0d22e4ab7a"
$TenantId = "c032627b-6715-4e39-9990-bcf48ee5e0c5"
$CertificateThumbprint = "4619B79D13DF75AC5A207C0692FAA2AF537007EF"

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

You are connected to Microsoft Graph. An excellent way to verify is to run the below cmdlet.

PS C:\> Get-MgContext

ClientId               : 3c17a3d6-8f7f-4407-b76f-ff0d22e4ab7a
TenantId               : c032627b-6715-4e39-9990-bcf48ee5e0c5
Scopes                 : {User.Read.All}
AuthType               : AppOnly
TokenCredentialType    : ClientCertificate
CertificateThumbprint  : 4619B79D13DF75AC5A207C0692FAA2AF537007EF
CertificateSubjectName :
Account                :
AppName                : myauth
ContextScope           : Process
Certificate            :
PSHostVersion          : 5.1.19041.3031
ManagedIdentityId      :
ClientSecret           :
Environment            : Global

Method 3: Connect MgGraph with Client Secret app

In the last method, we will show you how to create a Client Secret to the newly created application.

1️⃣ See the above steps to register a new application in Azure. In our example, we will use the same application we created earlier.

2️⃣ Assign API permissions. See the above steps to assign API permissions to the Azure application. In our example, we already assigned API permissions to the application we created earlier.

3️⃣ To create a Client Secret for your application in Microsoft Entra portal, follow these steps:

  1. Click on Certificates & secrets
  2. Click Client secrets > New client secret
  3. Type the description
  4. Select an expiration date
  5. Click Add
CSKXeHxsDI6pRYX12HicbCrvYXhGmrqKN2D4LptYNrhX167abHY6r0Byu8H9

4️⃣ Copy the client secret Value and save it

Note Note: Client secret values cannot be viewed except immediately after creation. Remember to save the secret when created before leaving the page.
kJh5plJoqIBOyr2HAWEYiywCKAYKe5DDdROMXR5z4FJrC7gwl8k659FjGYT2

5️⃣ Connect to Microsoft Graph with Client Secret. You need to change the below parameters values to connect to MS Graph with Client Secret:

# Configuration
$ClientId = "3c17a3d6-8f7f-4407-b76f-ff0d22e4ab7a"
$TenantId = "c032627b-6715-4e39-9990-bcf48ee5e0c5"
$ClientSecret = "HRt8Q~nJkPCq-Nvo-9fYBeQQMlqegHpNRfb3pcuQ"

# 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

That’s it! You successfully connected to Microsoft Graph PowerShell!

PS C:\> Get-MgContext

ClientId               : 3c17a3d6-8f7f-4407-b76f-ff0d22e4ab7a
TenantId               : c032627b-6715-4e39-9990-bcf48ee5e0c5
Scopes                 : {User.Read.All}
AuthType               : AppOnly
TokenCredentialType    : ClientSecret
CertificateThumbprint  :
CertificateSubjectName :
Account                :
AppName                : myauth
ContextScope           : Process
Certificate            :
PSHostVersion          : 5.1.19041.3031
ManagedIdentityId      :
ClientSecret           : System.Security.SecureString
Environment            : Global

Conclusion

You learned how to connect to Microsoft Graph PowerShell with a self-signed certificate, client secret, and interactive mode. Remember to update MS Graph module to the latest version, create an application and assign API permissions if you connect with client secret or CBA. With CBA, there is no more user interactions, usernames, passwords, or MFA involved to run automated scripts.

Not a reader? Watch this related video tutorial:

5/5 - (1 vote)
Previous Post

How to Install PowerShell 7 on Windows 10/11

Next Post

Configuring Scopes when Connecting to the Microsoft Graph PowerShell API

Related Posts

Running Hyper-V and VMware Workstation on The Same Machine

August 15, 2024

How to Uninstall All Autodesk Products At Once Silently

July 29, 2024
Ftr5

How to Uninstall the Autodesk Genuine Service on Windows

July 29, 2024
Ftr19

How to Fix Windows Cannot Read the ProductKey From the Unattend Answer File in VirtualBox

July 26, 2024
Ftr25

How to Update Windows Terminal in Windows 10/11

July 26, 2024

How to Disable The Beep Sound in WSL Terminal on Windows

July 26, 2024

Leave a Reply Cancel reply

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

Recent Posts

  • How To Turn On uBlock Origin Extension in Chrome (2025)
  • Images Hidden Due To Mature Content Settings In CivitAI
  • Azure OpenAI vs Azure AI Hub, How to Choose the Right One for Your Needs

Categories

Stay in Touch

Discord Server

Join the Discord server with the site members for all questions and discussions.

Telegram Community

Jump in Telegram server. Ask questions and discuss everything with the site members.

Youtube Channel

Watch more videos, learning and sharing with Leo ❤❤❤. Sharing to be better.

Newsletter

Join the movement and receive our weekly Tech related newsletter. It’s Free.

General

Microsoft Windows

Microsoft Office

VMware

VirtualBox

Technology

PowerShell

Microsoft 365

Microsoft Teams

Email Servers

Copyright 2025 © All rights Reserved. Design by Leo with ❤

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory