๐ฑ Recipe ยท Intune & Device Management
Deploy a One-Time PowerShell Script via Intune to Run Disk Cleanup and Clear Windows Update Cache
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
Context
Why This Matters
Why this recipe matters
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 recipe
- 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
What you'll have when you finish
- A reusable Intune PowerShell script (
DiskCleanup-WUCacheReset.ps1) that stops Windows Update services, clearsSoftwareDistributionandcatroot2, restarts the services, and invokescleanmgr /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 & Considerations
Warnings and gotchas
- 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 โ
cleanmgrsignals completion even if nothing was actually cleaned. cleanmgr /VERYLOWDISKis 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 theStateFlagsregistry keys underHKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\*and usecleanmgr /sagerun:1instead.- Deleting
SoftwareDistributioncancels 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.Allis 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: trueunless 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
| Permission | Why It's Needed |
|---|---|
| DeviceManagementManagedDevices.Read.All | Look up the target device's Intune managedDevice ID, compliance state, and storage info |
| DeviceManagementManagedDevices.PrivilegedOperations.All | Trigger a syncDevice action so the device picks up the newly assigned script |
| DeviceManagementScripts.ReadWrite.All | Create and assign the PowerShell script object in Intune (required specifically โ Configuration.ReadWrite.All is insufficient) |
| Device.Read.All | Resolve the corresponding Entra ID device object to add as a group member |
| Group.ReadWrite.All | Create a temporary security group and add the device as a member so the script can be assigned |
The fastest way to get this done: just ask Dex. Copy the prompt below and paste it into your Dex conversation.
For IT Admins
Paste into Dex Pro
For End Users
How an employee would ask Dex for help
Deploy via the Microsoft Intune admin center
Sign in to the Microsoft Intune admin center (
intune.microsoft.com) as an Intune Administrator.Navigate to:
Devices โ Scripts and remediations โ Platform scripts โ + Add โ Windows 10 and later
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.
- Name:
On the Script settings tab:
- Upload the
DiskCleanup-WUCacheReset.ps1file (contents shown in the PowerShell tab). - 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.
- Upload the
On the Assignments tab, click Add groups and select a security group that contains only the target device (create one first under if needed).
Review the summary and click Add.
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).
Monitor results under:
Devices โ Scripts and remediations โ {script_name} โ Device status
Look for Succeeded or view error output for any failures.
After the script reports success, clean up: delete the temporary security group and, optionally, the script definition itself.
Deploy via Microsoft Graph
Deploying a one-time PowerShell script via Graph is a four-step workflow: create the script, create (or reuse) a target group, assign the script, then trigger a sync.
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,deviceIdThen 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}/syncDeviceExpect 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=managedDeviceEach run state includes runState (success, fail, scriptError, pending), lastStateUpdateDateTime, and resultMessage with stdout/stderr.
Deploy via PowerShell (Microsoft.Graph SDK)
The script below 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
- Prompts for the target device name and connects to Microsoft Graph with the required scopes.
- Resolves both the Intune
managedDeviceID and the Entra IDdeviceobject ID for the target. - Builds the Disk Cleanup / WU cache payload as a here-string and base64-encodes it.
- Creates the Intune
deviceManagementScriptviaInvoke-MgGraphRequest. - Creates a temporary security group and adds the device as a member.
- Assigns the script to the group and triggers a device sync.
- 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' -SkipSyncAfter the script runs on the device, verify via Get-MgBetaDeviceManagementDeviceManagementScriptDeviceRunState or the Intune portal, then delete the temporary group to keep the tenant tidy.
Next steps