Authentication and SDK Setup
Installing the Microsoft.Graph PowerShell Modules
Install the device management modules from the PowerShell Gallery:
Install-Module Microsoft.Graph.DeviceManagement -Scope CurrentUser
Install-Module Microsoft.Graph.Groups -Scope CurrentUser
The older Microsoft.Graph.Intune module is deprecated. Microsoft split the Graph SDK into sub-modules in version 2.x; Microsoft.Graph.DeviceManagement covers Intune configuration profiles and compliance policies, while Microsoft.Graph.Groups handles group lookups for assignments. If you installed the monolithic Microsoft.Graph module, you already have these. Check your version with Get-InstalledModule Microsoft.Graph*. SDK 2.x changed cmdlet names: Get-MgDeviceManagementDeviceConfiguration replaced the old Get-IntuneManagedDevice pattern.
Registering an App with the Right Permissions
In the Entra admin center, register a new app under App registrations. Add API permissions for Microsoft Graph: DeviceManagementConfiguration.ReadWrite.All and DeviceManagementManagedDevices.ReadWrite.All. Both are application permissions; if you want delegated (user context) access, add the same permissions as delegated type. Grant admin consent for your tenant. Under Certificates & secrets, create a client secret or upload a certificate. Note the application (client) ID and tenant ID from the Overview page. For production automation, prefer certificate authentication over secrets.
Connecting Interactively and with Client Credentials
Interactive login with delegated permissions:
Connect-MgGraph -Scopes "DeviceManagementConfiguration.ReadWrite.All","DeviceManagementManagedDevices.ReadWrite.All" -NoWelcome
The -NoWelcome flag suppresses the banner. Your session persists until you call Disconnect-MgGraph or close the shell. For service principal authentication with a client secret:
$clientId = "your-app-id"
$tenantId = "your-tenant-id"
$clientSecret = "your-secret" | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($clientId, $clientSecret)
Connect-MgGraph -TenantId $tenantId -ClientSecretCredential $credential
With a certificate, use -CertificateThumbprint instead. The SDK refreshes tokens automatically; sessions last until you disconnect or the refresh token expires (typically 90 days for delegated, indefinite for application). For deeper background on Graph authentication patterns, see the PowerShell and Microsoft Graph API eBook.
Listing Existing Configuration Profiles
Retrieve all device configuration profiles with:
Get-MgDeviceManagementDeviceConfiguration | Select-Object DisplayName, Id, '@odata.type'
Output looks like:
DisplayName Id @odata.type
----------- -- -----------
Win10 Endpoint Protection a1b2c3d4-e5f6-7890-abcd-ef1234567890 #microsoft.graph.windows10GeneralConfiguration
iOS Email Settings f1e2d3c4-b5a6-7890-cdef-ab0987654321 #microsoft.graph.iosGeneralDeviceConfiguration
The @odata.type property tells you the platform and configuration type. Common values: #microsoft.graph.windows10GeneralConfiguration for Windows 10/11 general settings, #microsoft.graph.windows10EndpointProtectionConfiguration for security settings, #microsoft.graph.iosGeneralDeviceConfiguration for iOS. Filter by display name:
Get-MgDeviceManagementDeviceConfiguration -Filter "startswith(displayName,'Win10')"
Newer Settings Catalog profiles do not appear in this cmdlet's output. They live under a different endpoint and require Invoke-MgGraphRequest with https://graph.microsoft.com/beta/deviceManagement/configurationPolicies. The beta endpoint changes frequently; stick to v1.0 for production unless you need a feature only in beta. For a full overview of Intune resources in Graph, see Microsoft's Intune Graph API reference.
Creating a Windows 10 Device Configuration Profile
Building the JSON Payload for a Policy
A Windows 10 endpoint protection profile that enforces BitLocker and Windows Defender settings looks like this:
$profileJson = @{
"@odata.type" = "#microsoft.graph.windows10EndpointProtectionConfiguration"
displayName = "Win10 Security Baseline"
description = "BitLocker and Defender baseline for corporate devices"
bitLockerFixedDrivePolicy = @{
encryptionMethod = "aesCbc256"
requireEncryptionForWriteAccess = $true
}
defenderDetectedMalwareActions = @{
lowSeverity = "quarantine"
moderateSeverity = "quarantine"
highSeverity = "remove"
severeSeverity = "remove"
}
defenderPotentiallyUnwantedAppAction = "block"
defenderCloudBlockLevel = "high"
} | ConvertTo-Json -Depth 10
The @odata.type must match a valid configuration type. Find schema details in the Graph API documentation under deviceManagement resources, or export an existing profile from the Intune portal: edit a profile, open browser DevTools, watch the network tab when you save, and copy the JSON payload from the PUT request. Property names are case-sensitive. Use -Depth 10 with ConvertTo-Json to avoid truncation of nested objects.
Posting the Profile with Invoke-MgGraphRequest
Check if a profile with the same name exists before creating:
$existingProfile = Get-MgDeviceManagementDeviceConfiguration -Filter "displayName eq 'Win10 Security Baseline'"
if ($existingProfile) {
Write-Warning "Profile already exists with ID $($existingProfile.Id)"
} else {
$uri = "https://graph.microsoft.com/v1.0/deviceManagement/deviceConfigurations"
$newProfile = Invoke-MgGraphRequest -Method POST -Uri $uri -Body $profileJson -ContentType "application/json"
Write-Output "Created profile with ID $($newProfile.id)"
}
The response includes the new profile's ID, which you need for assignments. Store it in a variable or log it.
Handling Errors and Validating the Result
Common errors: HTTP 400 means invalid JSON or a property that does not exist in the schema; check property names and nesting. HTTP 403 means missing API permissions or admin consent. HTTP 409 means a profile with that displayName already exists; Intune enforces unique names within a configuration type. Wrap the call in try/catch:
try {
$newProfile = Invoke-MgGraphRequest -Method POST -Uri $uri -Body $profileJson -ContentType "application/json"
} catch {
Write-Error "Failed to create profile: $($_.Exception.Message)"
if ($_.Exception.Response.StatusCode -eq 400) {
Write-Error "Check JSON schema and property names"
}
}
Retrieve the profile immediately after creation to confirm:
Get-MgDeviceManagementDeviceConfiguration -DeviceConfigurationId $newProfile.id
Compare the returned settings with your JSON payload. Intune sometimes adds default values for properties you left unset.
Assigning Profiles to Entra Groups
Finding the Group ID for Targeting
You assign configuration profiles to Entra ID groups, not directly to devices. Find the group with:
Get-MgGroup -Filter "displayName eq 'All Windows Devices'"
Output includes the group's Id property, which you need for the assignment. If you manage groups by naming convention, filter with startswith:
Get-MgGroup -Filter "startswith(displayName,'Intune-')" | Select-Object DisplayName, Id
Dynamic groups work the same as static groups for assignments. Device groups and user groups behave differently: a device group applies the profile when the device checks in, regardless of who is logged in. A user group applies the profile to any device that user signs into. For most Windows configuration profiles, use device groups. Store the group ID in a variable:
$groupId = (Get-MgGroup -Filter "displayName eq 'All Windows Devices'").Id
Creating an Assignment with the Graph API
Assignments use a separate endpoint under the profile's resource. POST to /deviceManagement/deviceConfigurations/{profileId}/assignments with a JSON body specifying the target:
$profileId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
$assignmentJson = @{
assignments = @(
@{
target = @{
"@odata.type" = "#microsoft.graph.groupAssignmentTarget"
groupId = $groupId
}
}
)
} | ConvertTo-Json -Depth 10
$assignUri = "https://graph.microsoft.com/v1.0/deviceManagement/deviceConfigurations/$profileId/assign"
Invoke-MgGraphRequest -Method POST -Uri $assignUri -Body $assignmentJson -ContentType "application/json"
The /assign endpoint replaces all assignments; if you want to add to existing assignments without removing them, GET the current assignments first, append your new one to the array, and POST the combined list. For all devices in the tenant, use #microsoft.graph.allDevicesAssignmentTarget; for all users, use #microsoft.graph.allLicensedUsersAssignmentTarget. Exclude a group by adding an exclusion target:
@{
target = @{
"@odata.type" = "#microsoft.graph.groupAssignmentTarget"
groupId = $includeGroupId
}
}
@{
target = @{
"@odata.type" = "#microsoft.graph.exclusionGroupAssignmentTarget"
groupId = $excludeGroupId
}
}
Exclusions take precedence: if a device is in both groups, it does not receive the profile. List existing assignments with:
Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/deviceManagement/deviceConfigurations/$profileId/assignments"
Managing Compliance Policies and Status
Creating a Compliance Policy
Compliance policies enforce minimum security requirements. A Windows 10 compliance policy requiring a password and a recent OS version:
$complianceJson = @{
"@odata.type" = "#microsoft.graph.windows10CompliancePolicy"
displayName = "Win10 Minimum Compliance"
description = "Require password, encryption, and OS 22H2 or later"
passwordRequired = $true
passwordMinimumLength = 8
passwordRequiredType = "alphanumeric"
storageRequireEncryption = $true
osMinimumVersion = "10.0.19045"
osMaximumVersion = $null
} | ConvertTo-Json -Depth 10
$uri = "https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies"
$newCompliance = Invoke-MgGraphRequest -Method POST -Uri $uri -Body $complianceJson -ContentType "application/json"
The osMinimumVersion is a build number in the format major.minor.build. Windows 11 22H2 is 10.0.22621; Windows 10 22H2 is 10.0.19045. Set osMaximumVersion to $null or omit it entirely to allow any newer version. Assign compliance policies the same way as configuration profiles, using the policy's ID and the /assign endpoint. For a walkthrough of compliance workflows beyond policy creation, see Intune Device Management with Microsoft Graph API: Compliance, Configuration, Wipe.
Checking Device Compliance State
Query noncompliant devices with:
Get-MgDeviceManagementManagedDevice -Filter "complianceState eq 'noncompliant'" | Select-Object DeviceName, UserPrincipalName, ComplianceState, LastSyncDateTime
Possible states: compliant, noncompliant, conflict, error, unknown. A device reports unknown until it checks in with Intune for the first time after policy assignment. Check-ins happen every eight hours by default; you cannot force an immediate check-in from the Graph API. For per-policy compliance status:
$policyId = $newCompliance.id
Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies/$policyId/deviceStatuses"
Output includes each device's status for that policy: compliant, noncompliant, or error. The lastReportedDateTime property shows when the device last reported; if it is more than 24 hours old, the device may be offline or unenrolled. Compliance changes take time to propagate: after creating and assigning a policy, expect a delay of several hours before devices report their state. There is no instant sync from the API side.
Updating and Deleting Profiles Safely
Modify an existing profile with a PATCH request. Retrieve the profile ID, then send only the properties you want to change:
$profileId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
$updateJson = @{
description = "Updated baseline for Q2 2026"
defenderCloudBlockLevel = "high"
} | ConvertTo-Json -Depth 10
$uri = "https://graph.microsoft.com/v1.0/deviceManagement/deviceConfigurations/$profileId"
Invoke-MgGraphRequest -Method PATCH -Uri $uri -Body $updateJson -ContentType "application/json"
You cannot change the @odata.type of an existing profile. If you need to switch from windows10GeneralConfiguration to windows10EndpointProtectionConfiguration, delete the old profile and create a new one. To avoid mistakes, fetch the current profile JSON, modify it in PowerShell, then PATCH the result:
$existing = Invoke-MgGraphRequest -Method GET -Uri $uri
$existingObj = $existing | ConvertFrom-Json
$existingObj.defenderCloudBlockLevel = "high"
$existingObj.description = "Updated baseline for Q2 2026"
$updatedJson = $existingObj | ConvertTo-Json -Depth 10
Invoke-MgGraphRequest -Method PATCH -Uri $uri -Body $updatedJson -ContentType "application/json"
Use -Depth 10 with ConvertTo-Json to prevent truncation of nested objects like bitLockerFixedDrivePolicy. Without it, PowerShell converts deep structures to strings, and the PATCH fails with HTTP 400. Delete a profile with:
Invoke-MgGraphRequest -Method DELETE -Uri $uri
Warning: Deleting a profile removes it from all assigned devices on their next check-in. Devices revert to default settings for any configuration managed by that profile. There is no undo; back up the JSON before deletion.
Export a profile to JSON before deleting:
$profile = Invoke-MgGraphRequest -Method GET -Uri $uri
$profile | ConvertTo-Json -Depth 10 | Out-File "backup-$profileId.json"
Store the backup in version control. If you need to restore, POST the JSON to the deviceConfigurations endpoint; Intune creates a new profile with a new ID, so reassign it to groups afterward.
Automating Profile Deployment with Scripts
Storing Profiles as JSON Files in Git
Keep each profile in a separate JSON file under a profiles/ directory:
profiles/
win10-bitlocker.json
win10-defender.json
ios-passcode.json
android-work-profile.json
Each file contains the profile definition without the id property (Intune assigns that on creation). Example win10-bitlocker.json:
{
"@odata.type": "#microsoft.graph.windows10EndpointProtectionConfiguration",
"displayName": "Win10 BitLocker Enforcement",
"description": "Require BitLocker on fixed and OS drives",
"bitLockerFixedDrivePolicy": {
"encryptionMethod": "aesCbc256",
"requireEncryptionForWriteAccess": true
},
"bitLockerSystemDrivePolicy": {
"encryptionMethod": "aesCbc256",
"startupAuthenticationRequired": true,
"startupAuthenticationTpmUsage": "required"
}
}
Commit these files to Git. On every change, update the JSON and commit. Your deployment script reads the directory and applies all profiles to Intune, creating new ones or updating existing ones that match by displayName.
Idempotent Deployment Pattern
This script checks if each profile exists, creates it if missing, updates it if changed:
$profileFiles = Get-ChildItem -Path "profiles" -Filter "*.json"
foreach ($file in $profileFiles) {
$profileJson = Get-Content $file.FullName -Raw
$profileObj = $profileJson | ConvertFrom-Json
$displayName = $profileObj.displayName
$existing = Get-MgDeviceManagementDeviceConfiguration -Filter "displayName eq '$displayName'"
if ($existing) {
Write-Output "Updating $displayName"
$uri = "https://graph.microsoft.com/v1.0/deviceManagement/deviceConfigurations/$($existing.Id)"
Invoke-MgGraphRequest -Method PATCH -Uri $uri -Body $profileJson -ContentType "application/json"
} else {
Write-Output "Creating $displayName"
$uri = "https://graph.microsoft.com/v1.0/deviceManagement/deviceConfigurations"
Invoke-MgGraphRequest -Method POST -Uri $uri -Body $profileJson -ContentType "application/json"
}
}
Write-Output "Deployment complete: $($profileFiles.Count) profiles processed"
This approach is idempotent: run it multiple times without creating duplicates. For beta-only features like Settings Catalog profiles, use Select-MgProfile beta before connecting. Wrap each operation in try/catch and log errors to a file for review. In a CI/CD pipeline, authenticate with a service principal, run this script on every merge to main, and send the summary to Slack or email. For more on Graph automation in pipelines, see Automate Microsoft 365 with PowerShell and the Microsoft Graph API.
Next Steps and Production Checklist
You now have the tools to script Intune configuration at scale. Before running these scripts in production, work through this checklist:
- Test every profile in a pilot group before assigning to all devices. Create a
Pilot-Devicesgroup and assign new profiles there first. - Use certificate-based authentication for service principals in automation. Store the certificate in Azure Key Vault or a hardware security module, never in a plain file.
- Version your JSON profiles in Git with meaningful commit messages. Tag releases so you can roll back to a known-good state.
- Add error handling and logging to every script. Write successes and failures to a log file with timestamps and profile IDs.
- Document the
@odata.typeand purpose of each profile in a README. Future administrators will thank you. - Monitor compliance state daily. Query noncompliant devices and investigate why they fail; common causes are outdated OS versions, disabled services, or conflicting policies.
- Audit API permissions quarterly. Remove any permission your scripts no longer need.
For deeper coverage of Intune automation workflows, including app deployment and Autopilot provisioning, see Intune Management with PowerShell. The Intune via Graph API Cheat Sheet provides quick reference for endpoints, payloads, and common filters. Next, explore conditional access policies and group-based licensing to round out your Microsoft 365 automation toolkit.
Frequently Asked Questions
Can I use the older MSGraph or AzureAD modules for Intune automation?
The Microsoft.Graph.Intune module is deprecated and no longer receives updates. It does not support newer profile types like Settings Catalog or compliance policies added after 2021. Use Microsoft.Graph.DeviceManagement instead. The AzureAD module does not cover Intune at all; it only handles Entra ID objects like users and groups. Migrate to the current SDK to avoid compatibility issues and missing features.
How do I find the correct @odata.type for a configuration profile?
Create a sample profile in the Intune portal, open browser DevTools, switch to the Network tab, and save the profile. Find the PUT or POST request and examine the JSON payload; the @odata.type is at the top. Alternatively, consult the Intune Graph API documentation under deviceManagement resources. Common types: #microsoft.graph.windows10GeneralConfiguration for general Windows settings, #microsoft.graph.windows10EndpointProtectionConfiguration for security settings, #microsoft.graph.iosGeneralDeviceConfiguration for iOS.
Why does my compliance policy assignment not take effect immediately?
Devices check in with Intune every eight hours by default. After assigning a compliance policy, expect a delay of up to eight hours before devices report their status. You cannot force an immediate sync from the Graph API. Users can manually sync from the Company Portal app or Settings > Accounts > Access work or school > Info > Sync. Compliance state also depends on the device being online and able to reach Intune endpoints.
What permissions are needed for a service principal to manage Intune policies?
Grant DeviceManagementConfiguration.ReadWrite.All for configuration profiles and DeviceManagementManagedDevices.ReadWrite.All for compliance policies and device actions. Both are application permissions; add them in the Entra app registration under API permissions > Microsoft Graph, then grant admin consent. For group assignments, add Group.Read.All or GroupMember.Read.All. Use the principle of least privilege: if your script only reads profiles, grant .Read.All instead of .ReadWrite.All.
How do I test a policy change without affecting production devices?
Create a pilot group in Entra ID, add a few test devices or users, and assign the new or updated profile to that group only. Monitor compliance and device state for 24โ48 hours. If the pilot succeeds, expand the assignment to production groups. For high-risk changes like BitLocker enforcement, use a phased rollout: assign to 10% of devices, wait a week, then expand. Always keep a rollback plan: export the current profile JSON before updating.