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/

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/

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.

2 Comments

  1. Paulina said:

    Hello I would like to know what type of access you need to request to your SharePoint administrator in order to get messages from Microsoft teams Channels and create OneNote notebooks using Graph requests from PowerShell.

    January 8, 2021
    Reply

Leave a Reply

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