Listen to this Post

Introduction:
Microsoft Intune has become the cornerstone of modern endpoint management, enabling organizations to secure devices and applications from a cloud-native console. As cyber threats evolve, automation through Microsoft Graph API and PowerShell is no longer optional—it’s a necessity for enforcing consistent security policies and identity controls. Drawing from the real-world insights in the Microsoft Intune Cookbook, Second Edition by Andrew Taylor, this article provides a hands‑on guide to automating Intune tasks, hardening your environment, and streamlining identity‑driven security.
Learning Objectives:
- Understand how to leverage Microsoft Graph API for Intune automation and reporting.
- Implement PowerShell scripts to enforce security baselines, compliance policies, and conditional access.
- Integrate identity management with Intune for robust endpoint protection and automated remediation.
You Should Know:
- Setting Up the Microsoft Graph PowerShell SDK for Intune Management
Before automating Intune, you need a secure and authenticated environment to interact with Microsoft Graph. The Graph PowerShell SDK provides cmdlets that wrap the Graph API, making it easier to manage Intune objects.
Step‑by‑step guide:
1. Install the SDK (run as administrator):
Install-Module Microsoft.Graph -Scope CurrentUser
2. Connect to Graph with the required scopes (e.g., for Intune read/write):
Connect-MgGraph -Scopes "DeviceManagementConfiguration.ReadWrite.All", "DeviceManagementManagedDevices.ReadWrite.All", "DeviceManagementApps.ReadWrite.All", "DeviceManagementServiceConfig.ReadWrite.All"
3. Verify the connection:
Get-MgContext
This displays the authenticated tenant and scopes.
- Test a simple query to list all managed devices:
Get-MgDeviceManagementManagedDevice | Select-Object DeviceName, OperatingSystem, ComplianceState
What this does: The SDK simplifies authentication and provides cmdlets for common Intune tasks, eliminating the need to manually construct HTTP requests. Always use the least‑privilege scopes required for your automation.
2. Automating Device Enrollment with PowerShell and Graph
Automated enrollment ensures that new devices are immediately compliant and managed. You can use the Graph API to trigger enrollment policies or check enrollment status.
Step‑by‑step guide:
- Retrieve enrollment profiles (e.g., Windows Autopilot deployment profiles):
Get-MgDeviceManagementWindowsAutopilotDeploymentProfile | Format-List DisplayName, Id
- Assign a profile to a device (requires the device’s Azure AD device ID):
$profileId = "your-profile-id" $deviceId = "azure-ad-device-id" New-MgDeviceManagementWindowsAutopilotDeviceIdentityAssignment -WindowsAutopilotDeviceIdentityId $deviceId -DeploymentProfileId $profileId
3. Monitor enrollment status for all Autopilot devices:
Get-MgDeviceManagementWindowsAutopilotDeviceIdentity | Where-Object {$_.DeploymentState -ne "success"} | Select-Object SerialNumber, DeploymentState, LastContactedDateTime
What this does: Automating profile assignment and monitoring reduces manual overhead and helps quickly identify stalled enrollments. Combine with Azure Automation for scheduled checks.
3. Implementing Conditional Access Policies via Graph API
Conditional Access is the heart of identity‑driven security. You can create, update, and enforce policies programmatically to ensure consistent access rules across your tenant.
Step‑by‑step guide:
- Define a new conditional access policy (JSON structure) using the Graph API directly with PowerShell’s
Invoke-MgGraphRequest:$policyJson = @" { "displayName": "Require MFA for iOS/Android Intune Enrollment", "state": "enabled", "conditions": { "applications": { "includeApplications": ["0000000a-0000-0000-c000-000000000000"] }, Microsoft Intune app ID "clientAppTypes": ["mobileAppsAndDesktopClients"], "platforms": { "includePlatforms": ["iOS", "android"] } }, "grantControls": { "builtInControls": ["mfa"], "operator": "OR" } } "@ Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies" -Body $policyJson -ContentType "application/json"
2. List existing policies to audit current settings:
Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies" | ConvertFrom-Json | Select-Object -ExpandProperty value
3. Update a policy (e.g., change state to disabled):
$policyId = "policy-guid"
$updateJson = '{ "state": "disabled" }'
Invoke-MgGraphRequest -Method PATCH -Uri "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies/$policyId" -Body $updateJson -ContentType "application/json"
What this does: Automating policy management ensures rapid response to new threats (e.g., disabling a misconfigured policy) and enforces security baselines across the organization.
4. Deploying Security Baselines and Configuration Profiles
Intune’s security baselines (e.g., for Windows 10/11, Microsoft Edge) provide pre‑configured settings that align with Microsoft security recommendations. You can automate their assignment and customization.
Step‑by‑step guide:
1. List available security baselines:
Get-MgDeviceManagementConfigurationSettingTemplate | Where-Object {$_.DisplayName -like "security baseline"} | Format-Table DisplayName, Id
2. Create a new baseline profile from a template:
$templateId = "template-id"
$profile = @{
displayName = "Custom Windows Security Baseline"
description = "Automated deployment of security settings"
settings = @(
@{ "@odata.type" = "microsoft.graph.deviceManagementConfigurationSetting"; settingInstance = @{ "@odata.type" = "microsoft.graph.deviceManagementConfigurationChoiceSettingInstance"; settingDefinitionId = "device_vendor_msft_policy_config_windowsdefendersecuritycenter_hidewindowssecuritynotificationareacontrol"; choiceSettingValue = @{ value = "device_vendor_msft_policy_config_windowsdefendersecuritycenter_hidewindowssecuritynotificationareacontrol_1" } } }
)
}
New-MgDeviceManagementConfigurationPolicy -BodyParameter $profile
3. Assign the profile to an Azure AD group:
$policyId = "new-policy-id"
$assignment = @{
target = @{
"@odata.type" = "microsoft.graph.groupAssignmentTarget"
groupId = "azure-ad-group-id"
}
}
New-MgDeviceManagementConfigurationPolicyAssignment -DeviceManagementConfigurationPolicyId $policyId -BodyParameter $assignment
What this does: Automating baseline deployment ensures that every new device inherits hardened settings without manual intervention, reducing the attack surface.
- Monitoring and Reporting with Intune Data Warehouse and PowerShell
The Intune Data Warehouse provides a historical view of your environment. Combining it with PowerShell allows you to generate custom reports and alerts.
Step‑by‑step guide:
- Enable the Intune Data Warehouse in the Azure portal (if not already enabled).
- Obtain the warehouse URL and access token (using Graph):
$warehouse = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/beta/deviceManagement/reports/exportJobs" Extract the warehouse link from the response
- Query the warehouse using OData (example to get device compliance history):
$warehouseUrl = "https://yourtenant.analytics.manage.microsoft.com/DataWarehouse/v1.0/" $complianceData = Invoke-RestMethod -Uri "${warehouseUrl}deviceCompliance" -Headers @{Authorization = "Bearer $accessToken"} $complianceData.value | Export-Csv -Path "compliance_report.csv" -NoTypeInformation - Automate weekly reports with Azure Automation or a scheduled task.
What this does: Continuous monitoring helps detect non‑compliant devices and trends, enabling proactive remediation before security gaps widen.
6. Troubleshooting Common Intune Issues Using PowerShell
When devices fail to enroll or policies don’t apply, PowerShell scripts can quickly pinpoint the cause.
Step‑by‑step guide:
- Get detailed device information including last sync time, compliance status, and errors:
Get-MgDeviceManagementManagedDevice -Filter "deviceName eq 'WORKSTATION01'" | Select-Object DeviceName, ComplianceState, LastSyncDateTime, UserPrincipalName, DeviceRegistrationState
- Check the device’s enrolled user and its assigned policies:
$device = Get-MgDeviceManagementManagedDevice -Filter "deviceName eq 'WORKSTATION01'" $device | Get-MgDeviceManagementManagedDeviceAssignmentFilter | Select-Object Target
- Trigger a remote sync on a problematic device:
Invoke-MgDeviceManagementManagedDeviceSync -ManagedDeviceId $device.Id
- Review Intune logs (on Windows devices, check
%ProgramData%\Microsoft\IntuneManagementExtension\Logs). For automation, use PowerShell to remotely collect logs viaInvoke-Command.
What this does: Rapid troubleshooting reduces downtime and ensures that security policies are consistently applied.
7. Best Practices for Secure Intune Automation
Automation scripts themselves must be secured to avoid becoming an attack vector.
Step‑by‑step guide:
- Use managed identities in Azure Automation instead of storing service principal credentials.
- Store secrets in Azure Key Vault and retrieve them at runtime:
$secret = Get-AzKeyVaultSecret -VaultName "YourVault" -Name "GraphClientSecret" -AsPlainText
- Scope Graph permissions to the minimum required (e.g., use application permissions only when necessary and restrict to specific resources).
- Enable logging for all automation scripts (send logs to Azure Log Analytics) and set up alerts for anomalies.
- Regularly review delegated permissions granted to users running scripts.
What this does: Protects your automation infrastructure from credential theft and misuse, aligning with Zero Trust principles.
What Undercode Say:
- Automation is force multiplier: Leveraging Graph and PowerShell in Intune reduces manual errors and enforces consistent security across thousands of endpoints.
- Security is identity‑first: Conditional Access and compliance policies must be tightly integrated with Intune to close gaps before they are exploited.
- Continuous monitoring pays off: Proactive reporting and troubleshooting scripts help maintain a strong security posture and reduce mean time to remediation.
The Intune Cookbook’s practical approach reminds us that theory must translate into repeatable, secure actions. By embedding these PowerShell and Graph techniques into daily operations, organizations can transform Intune from a simple MDM into a dynamic security enforcement engine.
Prediction:
As hybrid work becomes permanent, Intune’s role will expand beyond device management into a unified security policy hub. Expect deeper integration with Microsoft Sentinel for real‑time threat response, and AI‑driven automation that can automatically quarantine compromised devices based on risk signals. The skills covered here—automation, identity, and API mastery—will be the foundation of the next generation of endpoint security operations.
▶️ Related Video (78% Match):
🎯Let’s Practice For Free:
IT/Security Reporter URL:
Reported By: Eantoniadi Just – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


