Introduction:
Microsoft Graph API provides a unified programmability model that allows developers to access a wide range of Microsoft 365 services. Connecting to Microsoft Graph API from PowerShell allows you to automate tasks, retrieve data, and perform various operations within your Microsoft 365 environment. In this guide, we’ll walk through the steps to set up and authenticate a PowerShell script to interact with Microsoft Graph API.
Step 1: Register an Application in Azure AD
- Navigate to the Azure Portal.
- In the “Azure Active Directory” section, go to “App registrations” and create a new registration for your application.
- Note down the “Application (client) ID” and “Directory (tenant) ID.”
- Generate a client secret under “Certificates & Secrets” and save the secret value.
- Assign the required API permissions to your application.
Step 2: Install Required Modules
Open a PowerShell console and install the necessary modules:
#PowerShell
Install-Module -Name Microsoft.Graph -Force -AllowClobber
Step 3: Authenticate and Get Access Token
Use the PowerShell script to authenticate and obtain an access token:
#PowerShell
# Import the required modules
Import-Module Microsoft.Graph
# Define your application details
$clientID = "<Your-App-Client-ID>"
$tenantID = "<Your-Tenant-ID>"
$clientSecret = "<Your-App-Client-Secret>"
$resource = "https://graph.microsoft.com"
# Authenticate to get an access token
$tokenEndpoint = "https://login.microsoftonline.com/$tenantID/oauth2/token"
$tokenBody = @{
grant_type = "client_credentials"
client_id = $clientID
client_secret = $clientSecret
resource = $resource
}
$tokenResponse = Invoke-RestMethod -Uri $tokenEndpoint -Method Post -Body $tokenBody
# Output the access token
$tokenResponse.access_token
Step 4: Make a Request to Microsoft Graph API
Replace the $graphEndpoint
variable with the specific API endpoint you want to access:
#PowerShell
# Use the access token to make a request to Microsoft Graph API
$graphEndpoint = "https://graph.microsoft.com/v1.0/me" # Example endpoint
$headers = @{
Authorization = "Bearer $($tokenResponse.access_token)"
}
# Make the request
$response = Invoke-RestMethod -Uri $graphEndpoint -Headers $headers -Method Get
# Output the response
Write-Output $response
Step 5: Run the Script
Save your PowerShell script and run it in your PowerShell environment. Ensure that you have the required permissions and that your script executes without errors.
This script is a basic example, and you might need to adjust it based on your specific requirements and the Microsoft Graph API endpoints you want to interact with. Always refer to the Microsoft Graph API documentation for the latest information and endpoint details.
If you have any requirements or any issues with the existing script, please contact us at BrainfoTech!
By Ahamed Jaharan