How to Make Microsoft Graph Request using PnP and Office 365 CLI

Information Circuit Board Graphics Concept

Microsoft Graph has a lot of commands that you can use to do some tasks. That will require you to manage and built the OAuth and from there make the request to Graph. But you can use the PnP PowerShell to perform this task. The commands will enable all of this and you don’t have to manage anything.

The first step is to authenticate with the required scopes. Note that the user that will log in need to have a level of permission to authorize the Application to send the Access Token. Check the next link if you want to know more about the level of permission. In this sample, I will use the request to know about the user that made the request.

You can easily adapt this to do other types of requests. Verify that you have the correct scopes if you are doing another request to Microsoft Graph.

PnP PowerShell

Connect-PnPOnline -Scopes "Directory.Read.All", "User.Read.All" 
$accesstoken = Get-PnPGraphAccessToken 

Invoke-RestMethod -Headers @{Authorization = "Bearer $accesstoken" } -Uri https://graph.microsoft.com/v1.0/me/
How to make Microsoft Graph request using PnP and Office 365 CLI
Setup an Alert when a File is Edited on OneDrive

Office 365 CLI

If you’re using the Office 365 CLI, by default, when you consent the application on your tenant it will have the scopes that we’re using on our sample.

o365 login
$accessToken = o365 util accesstoken get --resource https://graph.microsoft.com
Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken" } -Uri https://graph.microsoft.com/v1.0/me/
How to make Microsoft Graph request using PnP and Office 365 CLI
Office 365 CLI with Microsoft Graph Request

Conclusion

With these simple commands, you will unlock all the option of Microsoft Graph and then work with PowerShell. This can be useful to make some analyzes to your Office 365 or to retrieve any information.

About the Author:

Office 365 enthusiast. Sharing content with others helps everyone to grow and have more successful history to share with the world. A simple trick can make every day easier

Want to learn more? Check out DevOps Dataverse ALM using Power Apps CLI: a source centric approach.

Reference:

Ramalho, D. (2020). How to make Microsoft Graph request using PnP and Office 365 CLI. Available at: https://sharepoint-tricks.com/using-pnp-powershell-with-microsoft-graph/ [Accessed: 19th august 2020].

Share this on...

Rate this Post:

Share: