loading...
Cover image for PnP Tips - Retrieving Graph info from the command line

PnP Tips - Retrieving Graph info from the command line

jaloplo profile image Jaime López ・2 min read

This is the third article from the PnP Tips series and today I want to show you how easy it is to retrieve information from Microsoft Graph if you have a connection to your SharePoint Online using the command line.

I consider you know what is Microsoft Graph used for and what kind of information you can get. The more methods Microsoft is adding to the suite the more data you can work with from the users' actions. As an example, you can get people that are relevant for you based on the work you are doing.

Let's imagine your manager asks you for a list of all your tenant accounts to create some kind of reports base on their properties. The first thing we must do is open a PowerShell session and run the Connect-PnPOnline with your tenant URL as the parameter.

# Connecting to one of your site collections
Connect-PnPOnline https://<tenant name>.sharepoint.com/sites/<site URL>

# Connecting to the admin site
Connect-PnPOnline https://<tenant name>-admin.sharepoint.com

The next thing you should do is to prepare the stuff need to call the proper Graph method. One of the most important things is to set the authentication header, your call will not work if you don't have the proper access token. The authentication header must contain the word "Bearer" as the type followed by a valid token that we can easily get using the Get-PnPAccessToken command. Let check it out with this example:

$Token = Get-PnPAccessToken
$Headers = @{ Authorization = "Bearer $Token" }

Now we are ready to get our tenant users using Invoke-WebRequest command and passing the proper graph URL. Check the following gist where you will find the complete script.

At this point, you can ask your manager about the report she wants to have and discuss the proper data to be included.

I know this is a simple scenario with a simple request but tries to throw light on processes that can seem difficult or implies more effort than the needed. The Get-PnPAccessToken and Invoke-WebRequest commands work well together when you need to use Microsoft Graph to get information.

Discussion

pic
Editor guide