Skip to main content
The Ops Playbook

Stop the WMI Repair Ticket Loop with Proactive Remediation

A corrupted WMI repository silently blocks Software Center and Intune app installs until this proactive remediation script rebuilds it automatically.

Stop the WMI Repair Ticket Loop with Proactive Remediation
KBY Technologies15 min readTier L235 min

This playbook covers

Share

#The Old Way vs the New Way

The old way looks like this: a user opens Software Center or the Company Portal, clicks install, and gets a spinning wheel followed by a failure. The technician remotes in, checks the Software Center log, sees a WMI-related error code, opens an elevated command prompt, runs winmgmt /verifyrepository, confirms corruption, runs the repair manually, reboots the machine, and closes the ticket. Three days later the same user, or someone on the same image, raises the same ticket. Multiply that by a fleet of ten thousand endpoints and you have a permanent, low-grade drain on L1 and L2 capacity that never shows up as a single big incident but quietly eats hours every week.

The new way removes the human from the diagnostic loop entirely. A scheduled, SYSTEM-context script pair runs on every managed endpoint, silently checks WMI repository health, and repairs it before the failure ever reaches a user’s screen. The ticket is engineered out of existence because the fault is corrected before the symptom is generated. This article builds that pipeline using Microsoft Intune Proactive Remediations, backed by a Microsoft Graph API deployment so the whole thing is version-controlled and repeatable rather than a one-off console click.

WMI repository proactive remediation

#Prerequisites and Permissions

  • Microsoft Intune tenant with Endpoint analytics / Proactive remediations enabled (requires Windows Enterprise E3 or E5, Windows Education A3 or A5, or Windows VDA per user; Microsoft 365 F3, E3, E5, A3 and A5 include the first two).
  • An account assigned the Intune Administrator role, or a custom Intune role with the appropriate Device configurations permissions, for building and assigning script packages.
  • Application permission DeviceManagementScripts.ReadWrite.All (the permission the Graph reference lists for the deviceHealthScripts assign action) on an app registration if you deploy via Graph API rather than the portal.
  • PowerShell 5.1 or later on target endpoints (default on Windows 10 1607 and later).
  • A pilot Microsoft Entra ID security group, for example Ring0-WMI-Pilot, containing no more than fifty non-critical devices for the first fourteen days.
  • Read access to the Log Analytics workspace or Intune run reports used for monitoring remediation outcomes.

#Implementation Steps

  1. Action: Write the detection script that checks WMI repository consistency without making changes.

    Expected result: Exit code 0 when the repository is consistent, exit code 1 only when winmgmt explicitly reports it inconsistent, which triggers the paired remediation script. Unexpected output (an access error, or the localised text of a non-English Windows build) exits 2: Intune runs the remediation only on exit code 1, so these devices are reported with a DETECTION-ERROR line for a human to review instead of being reset.

    Evidence to capture: The console output line and exit code from a manual test run on a known-bad pilot device.

    1# Detect-WmiRepositoryHealth.ps1
    2# Run as SYSTEM via Intune Proactive Remediations
    3
    4try {
    5    $verify = winmgmt /verifyrepository 2>&1
    6    Write-Output "WinMgmt output: $verify"
    7
    8    if ($verify -match "inconsistent|not consistent") {
    9        Write-Output "WMI repository is INCONSISTENT - remediation required"
    10        exit 1
    11    }
    12    elseif ($verify -match "is consistent") {
    13        Write-Output "WMI repository is healthy"
    14        exit 0
    15    }
    16    else {
    17        Write-Output "DETECTION-ERROR: unable to parse winmgmt output - not remediating"
    18        exit 2
    19    }
    20}
    21catch {
    22    Write-Output "DETECTION-ERROR: $($_.Exception.Message)"
    23    exit 2
    24}

    Expected output on a healthy device:

    1WinMgmt output: WMI repository is consistent
    2WMI repository is healthy
  2. Action: Write the remediation script that repairs the repository in the least destructive way first, escalating only if required. A reset is destructive: it returns the repository to its default state and drops registrations that autorecover MOFs do not restore, so pilot it and keep the backup the script takes.

    Expected result: Repository is salvaged, or reset if salvage fails, and a registry timestamp is written for audit purposes. For a reset, the script stops WMI and its dependents, backs up the repository while the service is stopped, starts WMI again and runs the reset with it running, as Microsoft’s archived WMI repository guidance does, then restarts the dependents. Test this sequence on a pilot device before assigning the package. A reset is skipped, and the run exits 1 for escalation, if the device was reset in the last seven days, runs an agent on the protected list, or has an empty Autorecover MOFs list under HKLM\SOFTWARE\Microsoft\Wbem\CIMOM, which Microsoft’s guidance says to check before a reset. The reset runs only after the repository backup is confirmed on disk, a non-zero exit code from winmgmt /resetrepository stops the run before the reset timestamp is recorded, and older backups are pruned to the two newest only after the final verification reports a consistent repository.

    Evidence to capture: The registry key value, the local log, and, where a reset ran, the System log Service Control Manager entries (event ID 7036) for the WinMgmt stop and start, timestamped to the run.

    1# Remediate-WmiRepositoryHealth.ps1
    2# Run as SYSTEM via Intune Proactive Remediations
    3
    4$logPath = "C:\ProgramData\KBYRemediation\wmi-repair.log"
    5$regPath = "HKLM:\SOFTWARE\KBYTechnologies\WmiRemediation"
    6# Services of agents that rely on custom WMI classes; example only, edit for your estate
    7$protectedServices = @('CcmExec')
    8New-Item -ItemType Directory -Path "C:\ProgramData\KBYRemediation" -Force | Out-Null
    9
    10function Write-Log {
    11    param($Message)
    12    $stamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    13    "$stamp $Message" | Out-File -FilePath $logPath -Append -Encoding utf8
    14}
    15
    16try {
    17    Write-Log "Attempting salvage repair"
    18    $salvage = winmgmt /salvagerepository 2>&1
    19    Write-Log "Salvage output: $salvage"
    20
    21    Start-Sleep -Seconds 15
    22    $recheck = winmgmt /verifyrepository 2>&1
    23
    24    # Match "is consistent": plain "consistent" also matches "inconsistent"
    25    if (-not ($recheck -match "is consistent")) {
    26        $lastReset = (Get-ItemProperty -Path $regPath -Name LastResetUtc -ErrorAction SilentlyContinue).LastResetUtc
    27        if ($lastReset -and ((Get-Date).ToUniversalTime() - ([datetime]$lastReset).ToUniversalTime()).TotalDays -lt 7) {
    28            Write-Log "Reset skipped: last reset $lastReset is within 7 days - escalate"
    29            exit 1
    30        }
    31        if (Get-Service -Name $protectedServices -ErrorAction SilentlyContinue) {
    32            Write-Log "Reset skipped: protected agent installed - escalate"
    33            exit 1
    34        }
    35        # Reset rebuilds from the Autorecover MOFs list; do not reset if it is empty
    36        $autoMofs = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Wbem\CIMOM' -Name 'Autorecover MOFs' -ErrorAction SilentlyContinue).'Autorecover MOFs'
    37        if (-not ($autoMofs | Where-Object { $_ })) {
    38            Write-Log "Reset skipped: Autorecover MOFs list is empty - escalate"
    39            exit 1
    40        }
    41        # Stop-Service -Force also stops dependent services, so record the running ones
    42        $dependents = Get-Service -Name Winmgmt -DependentServices | Where-Object Status -eq 'Running'
    43        Write-Log "Salvage insufficient - performing full reset. Running dependents: $($dependents.Name -join ', ')"
    44        $backup = "C:\ProgramData\KBYRemediation\Repository-$(Get-Date -Format yyyyMMddHHmmss)"
    45        Stop-Service Winmgmt -Force -ErrorAction Stop
    46        try {
    47            # Back up the repository while the service is stopped, and confirm the copy exists
    48            Copy-Item -Path "$env:windir\System32\wbem\Repository" -Destination $backup -Recurse -Force -ErrorAction Stop
    49            if (-not (Test-Path "$backup\*")) { throw "Repository backup missing or empty - reset not attempted" }
    50            # Microsoft guidance runs the reset with WMI running; dependents stay stopped
    51            # so the reset does not fail with 0x8007041B
    52            Start-Service Winmgmt -ErrorAction Stop
    53            winmgmt /resetrepository
    54            if ($LASTEXITCODE -ne 0) { throw "winmgmt /resetrepository exited $LASTEXITCODE" }
    55            if (-not (Test-Path $regPath)) { New-Item -Path $regPath | Out-Null }
    56            Set-ItemProperty -Path $regPath -Name "LastResetUtc" -Value (Get-Date).ToUniversalTime().ToString("o")
    57        }
    58        finally {
    59            # Always bring WMI and its dependents back, even if the backup or reset failed
    60            Start-Service Winmgmt
    61            $dependents | Start-Service -ErrorAction SilentlyContinue
    62        }
    63    }
    64
    65    Start-Sleep -Seconds 10
    66
    67    $final = winmgmt /verifyrepository 2>&1
    68    Write-Log "Final verification: $final"
    69
    70    # New-Item -Force would recreate the key and drop LastResetUtc
    71    if (-not (Test-Path $regPath)) { New-Item -Path $regPath | Out-Null }
    72    Set-ItemProperty -Path "HKLM:\SOFTWARE\KBYTechnologies\WmiRemediation" -Name "LastRunUtc" -Value (Get-Date).ToUniversalTime().ToString("o")
    73    Set-ItemProperty -Path "HKLM:\SOFTWARE\KBYTechnologies\WmiRemediation" -Name "Outcome" -Value $final
    74
    75    if ($final -match "is consistent") {
    76        Write-Log "Remediation successful"
    77        # Prune only after a verified-consistent repository: keep the two newest backups
    78        Get-ChildItem "C:\ProgramData\KBYRemediation" -Directory -Filter "Repository-*" |
    79            Sort-Object Name -Descending | Select-Object -Skip 2 | Remove-Item -Recurse -Force
    80        exit 0
    81    }
    82    else {
    83        Write-Log "Remediation failed - manual escalation required"
    84        exit 1
    85    }
    86}
    87catch {
    88    Write-Log "Remediation script error: $($_.Exception.Message)"
    89    exit 1
    90}
  3. Action: Package both scripts as a Proactive Remediation script pair in the Intune admin center under Devices > Manage devices > Scripts and remediations > Create script package.

    Expected result: A script package exists with run context set to SYSTEM, “run script in 64-bit PowerShell” enabled, and both scripts attached.

    Evidence to capture: The generated script package ID from the portal URL or Graph response.

  4. Action: Create the same script package via Microsoft Graph (POST to /beta/deviceManagement/deviceHealthScripts) so the definition lives in source control rather than only in the portal.

    Expected result: A 201 Created response containing the new deviceHealthScript object ID.

    Evidence to capture: The full JSON response body saved to your automation repository’s deployment log.

    1{
    2  "displayName": "WMI Repository Health - Detect and Repair",
    3  "description": "Detects and repairs a corrupted WMI repository before Software Center or Intune app installs fail.",
    4  "publisher": "KBY Technologies - Ops Playbook",
    5  "runAsAccount": "system",
    6  "enforceSignatureCheck": false,
    7  "runAs32Bit": false,
    8  "detectionScriptContent": "BASE64_ENCODED_DETECTION_SCRIPT",
    9  "remediationScriptContent": "BASE64_ENCODED_REMEDIATION_SCRIPT",
    10  "roleScopeTagIds": ["0"]
    11}
  5. Action: Assign the script package to the pilot group with an eight-hour recurring schedule. Via Graph, POST a body like the one below to /beta/deviceManagement/deviceHealthScripts/{id}/assign, using the pilot group’s object ID.

    1{
    2  "deviceHealthScriptAssignments": [
    3    {
    4      "@odata.type": "#microsoft.graph.deviceHealthScriptAssignment",
    5      "target": {
    6        "@odata.type": "#microsoft.graph.groupAssignmentTarget",
    7        "groupId": "RING0_WMI_PILOT_GROUP_OBJECT_ID"
    8      },
    9      "runRemediationScript": true,
    10      "runSchedule": {
    11        "@odata.type": "#microsoft.graph.deviceHealthScriptHourlySchedule",
    12        "interval": 8
    13      }
    14    }
    15  ]
    16}

    This follows the deviceHealthScriptAssignment shape in the Graph beta reference: runRemediationScript must be true for the remediation to run, and the reference documents valid interval values of 1 to 23, matching the portal rule that an hourly interval must be less than 24 hours. Microsoft’s beta reference for the assign action documents a 204 No Content response with no body, so read the assignment back with a GET on /beta/deviceManagement/deviceHealthScripts/{id}/assignments and keep that output as evidence.

    Expected result: The Intune run summary shows scheduled executions across the pilot ring within the first schedule window.

    Evidence to capture: A screenshot or exported CSV of the per-device run status showing detection and remediation counts.

Stop the WMI Repair Ticket Loop with Proactive Remediation architecture diagram 2
  1. Action: Forward remediation outcomes to your Log Analytics workspace by exporting per-device run states from Microsoft Graph (deviceHealthScripts/{id}/deviceRunStates) or by shipping the local log file via your existing agent-based log collector. Microsoft does not document a built-in Log Analytics table for remediation results. The query below is an example that assumes your collector writes each deviceRunStates record to a custom table named KbyWmiRemediation_CL, keeping its remediationState value as a RemediationState column; rename both to match what your collector actually ingests.

    Expected result: A Kusto query against the remediation table returns events matching the registry timestamp written in step 2.

    Evidence to capture: The query result set, including device name, outcome, and timestamp.

    1# Sample KQL run against the Log Analytics workspace
    2KbyWmiRemediation_CL
    3| where TimeGenerated > ago(7d)
    4| summarize Remediated = countif(RemediationState == "success"),
    5            Failed = countif(RemediationState == "remediationFailed")
    6            by bin(TimeGenerated, 1d)
  2. Action: After seven clean days in the pilot ring with zero regressions, reassign the script package to production device groups in waves of twenty-five percent per day. The halt is manual: Intune does not pause the rollout itself, and the change owner named in the change record owns each go/no-go decision. As an automated gate, create an Azure Monitor log search alert rule on the step 6 query that notifies the change owner and the endpoint team when failed remediations exceed five percent of the previous wave, and do not start a wave while it is firing. Before each wave, the owner also reviews the previous wave’s run report and approves the next one; halt and follow the Rollback section if more than five percent of devices report remediation failure, if any DETECTION-ERROR results appear in bulk, or if WMI-related tickets rise.

    Expected result: Fleet-wide coverage within a working week, with the run report showing a declining remediation-needed percentage as corrupted repositories are cleared out.

    Evidence to capture: Daily coverage percentage exported from the Intune run report.

  3. Action: Configure your ticketing system to auto-tag or auto-suppress tickets referencing known WMI-related install failure codes (for example 0x80041002 or 0x8004100E) if a successful remediation event exists for that device within the preceding twenty-four hours.

    Expected result: Matching tickets are automatically closed or annotated rather than routed to a queue.

    Evidence to capture: The auto-closure rule log and a sample resolved ticket showing the correlation.

#Verification and Expected Evidence

Confirm the pipeline is working end to end before trusting it at scale. Pick one device from the pilot ring with a known-corrupted repository and run the detection script manually over PowerShell remoting. Intune keeps its own copy of the scripts, so pass your local copy with -FilePath; it runs under your admin account rather than SYSTEM.

Invoke-Command -ComputerName PILOT-WKS01 -FilePath .\Detect-WmiRepositoryHealth.ps1

Expected output before remediation:

1WinMgmt output: WMI repository is inconsistent
2WMI repository is INCONSISTENT - remediation required

Trigger the remediation with the Run remediation (preview) device action on the device’s Overview page in the Intune admin center. Microsoft documents it as an on-demand run of an existing script package on a single Windows device; the package does not have to be assigned to the device, but the device must be online and reachable through Intune and Windows Push Notification Service, and the action runs the package with its configured settings, which for this package means SYSTEM context. The remoting alternative, Invoke-Command -ComputerName PILOT-WKS01 -FilePath .\Remediate-WmiRepositoryHealth.ps1, runs under your admin account rather than SYSTEM and can perform the destructive repository reset, so use it only on a disposable test device, only after a full backup or a system restore point of that device has been taken and verified, and only once the run is approved in the change record. Then re-run detection. A healthy result plus a populated registry key confirms the loop closed without technician involvement:

Get-ItemProperty -Path "HKLM:\SOFTWARE\KBYTechnologies\WmiRemediation"

Expected output:

1LastRunUtc : 2024-11-04T09:12:47.0000000Z
2Outcome    : WMI repository is consistent

Cross-check the Intune portal run report for the same device and confirm in the package’s Device status view that the device’s latest run shows the issue detected and then fixed (in the Graph deviceRunStates record, remediationState is success) for the same time window. That three-way match, local registry, the local log in C:\ProgramData\KBYRemediation, and portal report, is your minimum evidence bar for sign-off. Where a reset ran, also check the System log for the Service Control Manager event ID 7036 entries for WinMgmt.

#Rollback

If the remediation script introduces a regression, for example a dependent agent that relies on custom WMI classes losing its provider registration after a repository reset, unassign the script package from the affected group immediately rather than disabling the schedule tenant-wide. This limits blast radius to the group already affected while you investigate.

  • Remove the group assignment in Intune admin center > Scripts and remediations > select the package > Assignments > remove the target group. This stops future runs only: it does not undo a reset already made, and a device may run the package once more before it picks up the change.
  • Re-register any custom WMI providers affected using the vendor’s supplied MOF or registration tool, since /resetrepository returns the repository to its default namespace state and drops non-default provider registrations. On a single device you can instead restore the repository copy the script saved under C:\ProgramData\KBYRemediation, with the Winmgmt service stopped.
  • Communicate the rollback in the change record with the specific device count and the failure signature observed.
  • Do not re-enable the schedule for that group until the underlying cause of the regression is understood and the remediation script has been updated to detect and skip devices running the affected dependent agent.

#Failure and Escalation Conditions

This automation is safe to run unattended within a defined tolerance. The following conditions should wake a human technician rather than being left to retry silently:

  • The remediation script exits with code 1 (repair failed) on the same device twice in a row within a 24-hour window.
  • WinMgmt service fails to start after a reset, evidenced by Service Control Manager event ID 7000 or 7009 in the System log.
  • More than five percent of the pilot ring reports a failed remediation in a single scheduled run (in deviceRunStates, a remediationState of remediationFailed or scriptError).
  • A dependent management agent (SCCM client, monitoring agent, backup agent) reports loss of WMI-dependent functionality within one hour of a remediation event on the same device.

Escalate to L3 Windows engineering with the device name, the full content of C:\ProgramData\KBYRemediation\wmi-repair.log, and the Intune run report ID. Local administrator rights on the affected device are sufficient for the repair itself; it does not need domain-level or Global Administrator rights.

#Measuring Ticket Deflection

Establish a baseline before deployment by pulling four weeks of ticket history filtered on categories such as “Software Center install failed”, “App deployment error”, and any ticket text matching WMI-related error codes. Record the weekly average count and the average technician handling time per ticket.

1# Example baseline pull against a ServiceNow instance table export (CSV already retrieved)
2awk -F',' '$3 ~ /0x80041002|0x8004100E|WMI/ {count++} END {print "Baseline weekly tickets:", count/4}' tickets_last_28_days.csv

After the production rollout completes, repeat the same query over the following four-week window and calculate the deflection percentage:

1deflection_pct=$(echo "scale=1; (1 - (post_count / baseline_count)) * 100" | bc)
2echo "Ticket deflection: ${deflection_pct}%"

Track this alongside the Log Analytics remediation success rate so you can attribute deflection to the automation rather than to seasonal ticket volume changes. A realistic target for a mature fleet with a WMI corruption pattern is sixty to eighty percent deflection within the first full reporting month, with the remainder representing genuinely novel failure modes that still warrant human diagnosis.

#References

For the platform mechanics behind this build, see Microsoft Learn: Proactive remediations in Microsoft Intune and Microsoft Learn: WMI command-line utilities and repository repair for the underlying winmgmt switches used in the detection and remediation scripts.

Evidence trail

Sources and verification

Primary documentation and external technical references used in this article.

  1. 01Microsoft Learn: Proactive remediations in Microsoft Intunelearn.microsoft.com
  2. 02Microsoft Learn: WMI command-line utilities and repository repairlearn.microsoft.com

About this page

Credited to

Dates

Published

Corrections

  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details
  • : Text damaged when it was saved (lost backslashes) was restored. Details
  • : Corrected during a review of published articles. Details
Reader Interaction

Comments

Add a thoughtful note on Stop the WMI Repair Ticket Loop with Proactive Remediation. Comments are checked for spam and held for moderation before appearing.

Loading comments...

Learn More About KBY

Was this useful?

Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.

Operate smarter, with fewer recurring tickets.

Receive new operational playbooks, incident-prevention guidance, automation scripts and recovery runbooks.