Introduction
Microsoft Graph is a RESTful web API that enables you to access Microsoft Cloud service resources, including Intune, to manage devices, applications, and policies programmatically. This guide will help you get started with Graph API and Intune, providing real examples and PowerShell code snippets to illustrate the key concepts.
Why Use Graph API with Intune?
Using Graph API with Intune offers several benefits:
- Automation: Automate repetitive tasks, such as device enrollment and policy assignment.
- Integration: Integrate Intune with other services and applications.
- Customization: Create custom solutions tailored to your organization’s needs.
Prerequisites
Before you begin, ensure you have the following:
- An Azure Active Directory (Azure AD) tenant.
- An Intune license.
- Appropriate permissions to access Intune data.
Setting Up Your Environment
-
- Register Your Application:
Registering your application creates a trust relationship between your app and the Microsoft identity platform. This trust is one-way: your app trusts the Microsoft identity platform, but not vice versa. Once created, the application object cannot be transferred between different tenants.- Sign in to the Microsoft Entra Admin Center.
- Navigate to Identity > Applications > App registrations and click on New registration.
- Select the Support Account Type who can access this API
- Enter a name for your application and register it. (e.g. Intune)
- Configure API Permissions:
- In your registered application, go to API permissions > Add a permission.
- Select Microsoft Graph and choose the necessary permissions (e.g.,
DeviceManagementManagedDevices.ReadWrite.All
). - For all Microsoft Graph Permissions, click here: Microsoft Graph permissions reference – Microsoft Graph | Microsoft Learn
- Add a client secret
- Select your application in App registrations, select your application.
- Select Certificates & secrets > Client secrets > + New client secret.
- Add a description for your client secret.
- Select an expiration for the secret or specify a custom lifetime.
- Client secret lifetime is limited to two years (24 months) or less. You can’t specify a custom lifetime longer than 24 months.
- Microsoft recommends that you set an expiration value of less than 12 months.
- Select Add.
- Record the secret’s value for use in your client application code. This secret value is never displayed again after you leave this page.
- Register Your Application:
The Connection Script
Here’s a script to load the appropriate modules and connect to Intune.
Replace the ID’s with your own ID’s that you have created in the section; Setting Up Your Environment.
# Script by Roland Verheijden - SparkleFlow # Set the ID's $TenantID="<your tenantID>" $ClientID="<your clientID>" $SecretKey="<your secretkey>" # # Is the IntuneWin32App Module installed? # ======================================= if(-not (Get-Module IntuneWin32App -ListAvailable)) { # Nope # Install it # ========== Install-Module -Name IntuneWin32App -Force -Confirm:$false -Scope CurrentUser } # Is the Microsoft.Graph.Intune Module installed? # =============================================== if(-not (Get-Module Microsoft.Graph.Authentication -ListAvailable)) { # Nope # Install it # ========== Install-Module -Name Microsoft.Graph.Authentication -Force -Confirm:$false -Scope CurrentUser } if(-not (Get-Module Microsoft.Graph.Groups -ListAvailable)) { # Nope # Install it # ========== Install-Module -Name Microsoft.Graph.Groups -Force -Confirm:$false -Scope CurrentUser } # Do I have my parameters to make the connections # =============================================== if (($TenantID -ne $null) -and ($ClientID -ne $null) -and ($SecretKey -ne $null)) { # Yep # Connect to Intune # ================= $Tokeninfo = Connect-MSIntuneGraph -TenantID $TenantID -ClientID $ClientID -ClientSecret $SecretKey # Create SecureString to connect to mgGraph # ========================================= $SecureClientSecret = ConvertTo-SecureString -String $SecretKey -AsPlainText -Force # Create a PSCredential Object Using the Client ID and Secure Client Secret # ========================================================================= $ClientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ClientID, $SecureClientSecret # Connect to Microsoft Graph Using the Tenant ID and Client Secret Credential # =========================================================================== Connect-MgGraph -TenantId $TenantID -ClientSecretCredential $ClientSecretCredential -NoWelcome } else { # Nope # Exit because there are parameters missing # ========================================= Write-Output "Parameters for the connection are missing!" exit } # Check if I need to refresh the token # ==================================== if ((Test-AccessToken) -eq $false) { # Yep # Refresh the token # ================= Clear-MsalTokenCache $Tokeninfo = Connect-MSIntuneGraph -TenantID $TenantID -ClientID $ClientID -ClientSecret $SecretKey }
Example 1: Listing Users
Here’s an example to retrieve the user IDs, names in your organization.
Use the connection script above with this part.
$users = Get-MgUser -All
$users | Select-Object Id, DisplayName, UserPrincipalName
Example 2: Listing Managed Devices
Here’s a simple example of how to list the names of the managed devices using Graph API and PowerShell.
Use the connection script above with this part.
# Get all devices
$devices = Get-MgDevice
# Display the names
$devices | Select-Object DisplayName
Example 3: Creating a Compliance Policy
Creating a compliance policy is another common task. Below is an example using PowerShell.
This script defines a compliance policy that requires a password with a minimum length of 6 characters, creates the policy, defines a scheduled action that blocks non-compliant devices immediately (0 hours grace period), and assigns the scheduled action to the compliance policy.
# Define the compliance policy with a scheduled action
$compliancePolicy = @{
"@odata.type" = "#microsoft.graph.windows10CompliancePolicy"
displayName = "Require Password"
description = "Policy that requires a password with a minimum length of 6 characters"
passwordRequired = $true
passwordMinimumLength = 6
scheduledActionsForRule = @(
@{
"@odata.type" = "#microsoft.graph.deviceComplianceScheduledActionForRule"
ruleName = "PasswordRequired"
scheduledActionConfigurations = @(
@{
"@odata.type" = "#microsoft.graph.deviceComplianceActionItem"
actionType = "block"
gracePeriodHours = 0
}
)
}
)
}
# Create the compliance policy
$policy = New-MgDeviceManagementDeviceCompliancePolicy -BodyParameter $compliancePolicy
Example 4: Check all Devices Compliance Status
To retrieve the compliance status of all devices:
Use the connection script above with this part.
$devices = Get-MgDevice
# Retrieve the compliance status of all managed devices
$managedDevices = Get-MgDeviceManagementManagedDevice -All
# Display the compliance status
$managedDevices | Select-Object DeviceName, ComplianceState
Conclusion
Starting with Graph API and Intune can significantly enhance your ability to manage devices and policies programmatically. By following the steps outlined in this guide and using the provided examples, you can begin leveraging the power of Graph API to automate and customize your Intune environment.
Recent Comments