Connecting to Graph API using Invoke-Webrequest
Let’s walk through how you can connect to the Microsoft Graph API using PowerShell’s Invoke-WebRequest command.
Setting the secret information
First, you’ll need a few things from Azure AD:
The application registration ID
The tenant ID
The API key (client secret) from your app registration
Here’s how you’d set those up in your script:
$AppId = "Application (Client) ID"
$client_secret = "Client secret"
$TenantId = "TenantName.onmicrosoft.com"
Creating the body of the token request
Next, you’ll build the body for your token request. Notice the scope property—this is the permission your app is asking for. In this example, we’re requesting the default permission for the application ID.
$body = @{
client_id = $AppId
scope = "https://graph.microsoft.com/.default"
client_secret = $client_secret
grant_type = "client_credentials"
}
Making the web request to get the token
Now, let’s actually request the token. We’ll use Invoke-WebRequest for this. (You could also use Invoke-RestMethod, but that’s more tailored for REST APIs, while Invoke-WebRequest is more general-purpose.)
We’re making a POST request to the Graph API’s token endpoint, sending our form data in the body.
Note: In PowerShell 6.0.0 and later, all web requests use basic parsing, so you don’t need to worry about the UseBasicParsing parameter.
$tokenRequest = `
Invoke-WebRequest `
-Method Post `
-Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" `
-ContentType "application/x-www-form-urlencoded" `
-Body $body `
-UseBasicParsing
Converting the Token response
The response you get back will be in JSON. To actually use the token, you’ll want to convert that JSON into a PowerShell object and grab the access_token property.
$token = ($tokenRequest.Content | ConvertFrom-Json).access_token
Using the token to create the headers for API request
Now that you have your token, you’ll need to set up your headers for the API request.
The Content-Type is set to JSON, and the Authorization header uses the bearer token you just got.
$authHeader1 = @{
'Content-Type' = 'application\json'
'Authorization' = "Bearer $token"
}
Setting the url (uri) for the API request
Here’s where you set the endpoint you want to hit. For example, to get a list of users:
$URL = "https://graph.microsoft.com/v1.0/users"
Sending the request to the API endpoint
Now you’re ready to send your GET request to the API.
Just use Invoke-WebRequest with the headers and URL you set up above.
$Users = Invoke-WebRequest -Headers $AuthHeader1 -Uri $URL
The response will be in JSON format. To work with the data, convert the content from JSON and select the Value property:
$result = ($Users.Content | ConvertFrom-Json).Value
And that’s it! You’ve just connected to the Graph API and pulled down some data using PowerShell.

