Automation & DevOps Deep-Dive

Automating Windows Updates Remediation with Intune

Transform reactive manual tasks into a proactive security model with advanced automation using Azure, Microsoft Graph API, and Intune. Complete technical implementation guide.

Ofir Gavish
Automation, PowerShell, Graph API
15 min read

Introduction

From Reactive to Proactive Security

Automating Windows Updates Remediation for Devices with errors on Intune Expedited Update reports transforms reactive manual tasks into a proactive security model.

This article provides an in-depth technical exploration of building this automation using Azure Automation, Microsoft Graph API, and Microsoft Intune.

Understanding Microsoft Graph API

The Challenge We Encountered

Initially, utilizing the Microsoft Graph API for device status retrieval appeared straightforward. However, specifying custom Intune policy names in the API calls produced confusing errors.

Discovery: The API requires specific built-in report identifiers like QualityUpdateDeviceStatusByPolicy rather than user-defined names.

Report Generation Workflow

Asynchronous Workflow Required

To fetch reports from Intune via Graph API, an asynchronous workflow is mandatory:

1

Initiate Report Generation

Using an HTTP POST request to trigger the creation of the report

2

Polling Status

Continuously checking via HTTP GET until status transitions from notStarted to completed

3

Downloading the Report

Upon completion, a downloadable ZIP file is provided, containing the JSON report

Example POST Request

POST https://graph.microsoft.com/beta/deviceManagement/reports/exportJobs
{
    "reportName": "QualityUpdateDeviceStatusByPolicy",
    "filter": "(PolicyId eq 'YOUR_POLICY_ID')",
    "format": "json"
}

Polling Example

do {
    $jobStatus = Invoke-MgGraphRequest -Uri $statusUri
    Start-Sleep -Seconds 5
} until ($jobStatus.status -eq "completed")

Technical Details: Parsing JSON Reports

Critical JSON Processing

The downloaded ZIP contains JSON with detailed device statuses. Parsing this JSON accurately is crucial for identifying devices requiring remediation.

JSON Parsing Implementation

$reportData = Get-Content "Report.json" | ConvertFrom-Json
$devicesWithErrors = $reportData | Where-Object { $_.CurrentDeviceUpdateStatus -eq "Error" }

foreach ($device in $devicesWithErrors) {
    Write-Host "Device: $($device.DeviceName), Error: $($device.LatestAlertMessage)"
}

Dynamic Management of Azure AD Groups

Intelligent Group Assignment

Devices identified with errors are dynamically added to Azure AD groups, facilitating targeted remediation. Here's how devices are programmatically added:

Adding Devices to Groups

PowerShell - Group Membership Management
New-MgGroupMember -GroupId $group.Id -DirectoryObjectId $device.AzureAdDeviceId

Automatic Cleanup Process

Additionally, devices that report a successful update status in subsequent checks are automatically removed from the Azure AD assignment group. This ensures the remediation process is precise, targeting only those devices still requiring attention!

Integrating Microsoft GitHub Repo Functions

Leveraging Official Microsoft Functions

To simplify managing Intune scripts, functions from Microsoft's official GitHub repository were integrated, providing standardized, reliable methods for creating, updating, and assigning scripts:

Create Scripts

Leveraging the New-MgDeviceManagementScript cmdlet to upload scripts to Intune

Update Scripts

The Update-MgDeviceManagementScript function allows easy modification and versioning

Manage Assignments

Using New-MgDeviceManagementScriptAssignment to handle script deployments efficiently

Implementation Examples

PowerShell - Script Management Functions
# Example: Deploy a new script
New-MgDeviceManagementScript -BodyParameter $scriptParams

# Example: Update existing script
Update-MgDeviceManagementScript -DeviceManagementScriptId $scriptId -BodyParameter $scriptParams

# Example: Assign script to a group
New-MgDeviceManagementScriptAssignment -DeviceManagementScriptId $scriptId -BodyParameter $assignmentParams

Deploying Remediation Scripts via Intune

Base64 Encoding Requirement

Intune expects scripts in Base64 encoding to ensure accurate transmission and storage, preserving the integrity of the content across different systems.

The Base64 encoding process converts the script's text into ASCII text, safe for transmission over networks and reliably decoded by Intune on endpoints.

Script Encoding Example

PowerShell - Base64 Encoding
$scriptText = Get-Content -Path "RemediationScript.ps1" -Raw
$scriptContent = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($scriptText))

What the Remediation Script Does on the Endpoint

Intelligent Update Blocker Detection

The PowerShell remediation script deployed through Intune is designed to intelligently check for common blockers that cause Windows updates to fail or get stuck.

It first inspects the system for pending reboots, which can prevent update installation from completing successfully. This is done by checking known registry keys such as:

Registry Key Monitoring

HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending
HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired
HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations

Smart Reboot Scheduling

If a pending reboot is detected, the script schedules a system restart during a low-usage time (e.g., 2 AM). This proactive approach helps avoid user disruption while ensuring the system can move forward with the update process.

Windows Update Component Reset

If no reboot is required, the script attempts to resolve other update-related issues by resetting the Windows Update components. This involves:

  • Stopping relevant services (BITS, wuauserv, cryptsvc, appidsvc)
  • Clearing the SoftwareDistribution folder
  • Triggering a forced Windows Update scan using UsoClient.exe StartScan

Self-Healing & Auditing

This script is fully self-healing and silent. It logs its operations to ensure traceability and auditing:

C:\ProgramData\Microsoft\IntuneManagementExtension\Logs\ExpeditedUpdateRemediation.log

This ensures that admins can verify its activity and effectiveness without requiring user input or manual checking.

Automating Across All Policies

Comprehensive Coverage Enhancement

The script was further enhanced to iterate through all available expedited update policies, ensuring comprehensive coverage across your entire Intune environment.

Policy Iteration Implementation

PowerShell - Multi-Policy Automation
$policies = Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/beta/deviceManagement/windowsQualityUpdateProfiles"
foreach ($policy in $policies.value) {
    # Execute report generation and remediation for each policy
}

Full Script

Complete Implementation Available

The full script with all the technical implementations discussed in this article can be found in my GitHub repository.

View Full Script on GitHub

Conclusion

This deep-dive demonstrates building robust automation through detailed Graph API interactions, JSON parsing, dynamic group management, and proactive remediation.

Enhanced Efficiency

Significantly improved operational efficiency through intelligent automation and proactive remediation strategies

Security Resilience

Strengthened security posture by ensuring Windows updates are consistently applied across all managed devices

By thoroughly addressing these technical complexities, we've transformed reactive manual processes into a proactive, automated security model.

Ofir Gavish

Ofir Gavish

Cloud Automation Architect | Microsoft MVP

Specializing in advanced automation solutions, Microsoft Graph API integrations, and enterprise-scale device management. Expert in transforming manual IT operations into intelligent, proactive systems.

Share this article

Related Articles