Deploy a One-Time PowerShell Script via Intune to Run Disk Cleanup and Clear Windows Update Cache

Prev Next

Remotely reclaim disk space on a managed Windows device by pushing a targeted PowerShell script through Intune.

Complexity: Intermediate. Impact: device-performance + storage + windows-update + remote-remediation + intune-scripts.

Why use this workflow

When a user reports their Windows device is running slowly, one of the most common root causes is critically low free disk space: especially when the Windows Update cache (C:\Windows\SoftwareDistribution) and catroot2 folder have grown large, or when temp files, update leftovers, and component store bloat have accumulated over months.

Rather than asking the end user to run Disk Cleanup manually (which many won't do correctly or at all), Intune admins can deploy a one-time PowerShell script that performs the cleanup silently in the SYSTEM context and runs at the next device check-in.

When to run this workflow

  • A user reports slow performance and the device shows less than ~15% free disk space
  • Windows Update failures or stuck downloads suggest a corrupted update cache
  • You want to reclaim space across many devices without touching each one
  • You need a quick remediation action that doesn't require a reboot or visit to the user's desk

Expected outcomes

  • A reusable Intune PowerShell script (DiskCleanup-WUCacheReset.ps1) that stops Windows Update services, clears SoftwareDistribution and catroot2, restarts the services, and invokes cleanmgr /VERYLOWDISK
  • A targeted assignment scoped to a single device (via a temporary security group) so only the intended machine runs the cleanup
  • A triggered device sync so the script executes at the next check-in rather than waiting for the 1-hour Intune script polling cycle
  • A clear audit trail in the Intune portal showing the script, its assignment, and per-device run results

Risks and considerations

  • Intune scripts run only once per device per assignment. If the script fails, you must re-create it (or change the script ID) to re-run it: cleanmgr signals completion even if nothing was actually cleaned.
  • cleanmgr /VERYLOWDISK is non-interactive and uses the default cleanup categories. It will not run if the disk is not actually low. For more aggressive cleanup, pre-populate the StateFlags registry keys under HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\* and use cleanmgr /sagerun:1 instead.
  • Deleting SoftwareDistribution cancels in-progress Windows Updates. Any partially downloaded updates will be re-downloaded on the next update scan. Don't run this during a critical patch cycle.
  • Permissions required are specific. Creating the script requires DeviceManagementScripts.ReadWrite.All: DeviceManagementConfiguration.ReadWrite.All is NOT sufficient, despite what the Graph docs sometimes imply.
  • Script assignments target groups, not individual devices. Create a dedicated security group (or use a dynamic-membership group) and delete it after execution to keep your tenant tidy.
  • Do not set enforceSignatureCheck: true unless your org signs all deployed scripts: otherwise the script will never run.
  • The script runs as SYSTEM by default. Do not put user-specific paths (e.g. $env:USERPROFILE) in it: they will resolve to the SYSTEM profile.

Required permissions

PermissionWhy it's needed
DeviceManagementManagedDevices.Read.AllLook up the target device's Intune managedDevice ID, compliance state, and storage info
DeviceManagementManagedDevices.PrivilegedOperations.AllTrigger a syncDevice action so the device picks up the newly assigned script
DeviceManagementScripts.ReadWrite.AllCreate and assign the PowerShell script object in Intune (required specifically: Configuration.ReadWrite.All is insufficient)
Device.Read.AllResolve the corresponding Entra ID device object to add as a group member
Group.ReadWrite.AllCreate a temporary security group and add the device as a member so the script can be assigned

Ask Dex

Paste the prompt into a Dex conversation.

Prompt for IT admins

Deploy a one-time PowerShell script via Intune to device {device_name} that stops Windows Update services, clears the SoftwareDistribution and catroot2 folders, restarts the services, and runs Disk Cleanup. Target only that device, trigger a sync so it runs promptly, and report back the script ID and group so I can clean them up afterward.

How an end user can ask Dex

My work computer is really slow and running low on disk space: can someone clean it up?

Manual steps (admin center)

  1. Sign in to the Microsoft Intune admin center (intune.microsoft.com) as an Intune Administrator.
  2. Go to Devices > Scripts and remediations > Platform scripts > + Add > Windows 10 and later.
  3. On the Basics tab, enter:
    • Name: Disk Cleanup & WU Cache Clear - {device_name}
    • Description: One-time: stops WU services, clears SoftwareDistribution and catroot2, restarts services, runs cleanmgr /VERYLOWDISK.
  4. On the Script settings tab:
    • Upload the DiskCleanup-WUCacheReset.ps1 file.
    • Run this script using the logged on credentials: No (run as SYSTEM).
    • Enforce script signature check: No.
    • Run script in 64 bit PowerShell Host: Yes.
  5. On the Assignments tab, click Add groups and select a security group that contains only the target device (create one first under Entra ID > Groups > New group if needed).
  6. Review the summary and click Add.
  7. Force execution by going to Devices > Windows > {device_name} > Sync. The script will run at the next check-in (typically within 15 minutes after the sync).
  8. Monitor results under Devices > Scripts and remediations > {script_name} > Device status. Look for Succeeded or view error output for any failures.
  9. After the script reports success, clean up: delete the temporary security group and, optionally, the script definition itself.

Microsoft Graph API

Deploying a one-time PowerShell script via Graph is a multi-step workflow: create the script, create (or reuse) a target group, assign the script, trigger a sync, then check results.

Step 1: Create the script

The script content must be base64-encoded UTF-8.

POST https://graph.microsoft.com/beta/deviceManagement/deviceManagementScripts
Content-Type: application/json

{
  "displayName": "Disk Cleanup & WU Cache Clear - {device_name}",
  "description": "One-time: stops WU services, clears SoftwareDistribution & catroot2, restarts services, runs cleanmgr /VERYLOWDISK",
  "scriptContent": "<base64-encoded PowerShell>",
  "runAsAccount": "system",
  "enforceSignatureCheck": false,
  "fileName": "DiskCleanup-WUCacheReset.ps1",
  "runAs32Bit": false
}

A 201 Created response returns the new script's id: save it as {script_id}.

Step 2: Look up the Entra ID device object and create a target group

GET /v1.0/devices?$filter=displayName eq '{device_name}'&$select=id,displayName,deviceId

Then create a security group containing that device:

POST /v1.0/groups

{
  "displayName": "CoAdmin-Script-{device_name}",
  "description": "Temporary group for Intune script deployment - safe to delete after script runs",
  "mailEnabled": false,
  "mailNickname": "CoAdmin-Script-{device_name}",
  "securityEnabled": true,
  "members@odata.bind": [
    "https://graph.microsoft.com/v1.0/devices/{entra_device_object_id}"
  ]
}

Step 3: Assign the script to the group

POST /beta/deviceManagement/deviceManagementScripts/{script_id}/assign

{
  "deviceManagementScriptAssignments": [
    {
      "target": {
        "@odata.type": "#microsoft.graph.groupAssignmentTarget",
        "groupId": "{group_id}"
      }
    }
  ]
}

Step 4: Trigger a device sync

POST /beta/deviceManagement/managedDevices/{managed_device_id}/syncDevice

Expect a 204 No Content response. The device will check in within 5-15 minutes and execute the script.

Step 5: Check results

GET /beta/deviceManagement/deviceManagementScripts/{script_id}/deviceRunStates?$expand=managedDevice

Each run state includes runState (success, fail, scriptError, pending), lastStateUpdateDateTime, and resultMessage with stdout/stderr.

PowerShell

This workflow uses the Microsoft.Graph PowerShell SDK to perform the full workflow: authenticate, build and base64-encode the payload script, create the Intune script object, create a target group, assign, and sync.

Prerequisites

  • PowerShell 5.1+ or PowerShell 7
  • Install-Module Microsoft.Graph -Scope CurrentUser
  • An account with Intune Administrator and Groups Administrator (or equivalent) roles

What the script does

  1. Prompts for the target device name and connects to Microsoft Graph with the required scopes.
  2. Resolves both the Intune managedDevice ID and the Entra ID device object ID for the target.
  3. Builds the Disk Cleanup / WU cache payload as a here-string and base64-encodes it.
  4. Creates the Intune deviceManagementScript via Invoke-MgGraphRequest.
  5. Creates a temporary security group and adds the device as a member.
  6. Assigns the script to the group and triggers a device sync.
  7. Prints the script ID, group ID, and a suggested cleanup command.

Because the script is idempotent-unsafe (creates new Graph objects each run), always supply a unique -DeviceName or delete the previous run's artifacts before re-running.

Running the script

# Basic usage
.\Deploy-DiskCleanupToIntuneDevice.ps1 -DeviceName 'DESKTOP-FP78FMK'

# Skip the immediate sync (let the next scheduled check-in pick it up)
.\Deploy-DiskCleanupToIntuneDevice.ps1 -DeviceName 'DESKTOP-FP78FMK' -SkipSync

After the script runs on the device, verify via Get-MgBetaDeviceManagementDeviceManagementScriptDeviceRunState or the Intune portal, then delete the temporary group to keep the tenant tidy.