ANAVEM
Languagefr
How to Automate Disk Cleanup for Windows 11 Upgrades Using Intune Remediation

How to Automate Disk Cleanup for Windows 11 Upgrades Using Intune Remediation

Create and deploy Intune Proactive Remediation scripts that automatically detect low disk space and guide users through cleanup to ensure successful Windows 11 upgrades.

March 21, 2026 15 min 0
mediumintune 8 steps 15 min

Why Automate Disk Cleanup for Windows 11 Upgrades?

Windows 11 upgrades require significantly more free disk space than previous Windows versions—Microsoft recommends at least 64GB of available storage on the system drive. Many organizations discover that a substantial portion of their device fleet lacks sufficient space for smooth upgrades, leading to failed deployments and frustrated users.

Traditional approaches like manual cleanup instructions or basic Group Policy settings often fall short because they don't provide real-time detection or user-friendly guidance. Users either ignore cleanup requests or accidentally delete important files while trying to free up space.

How Does Intune Proactive Remediation Solve This Challenge?

Microsoft Intune's Proactive Remediation feature, part of the Endpoint Analytics suite, provides an elegant solution by combining automated detection with guided user interaction. The system continuously monitors device health and can automatically trigger remediation scripts when issues are detected.

For disk space management, this means you can deploy scripts that detect low storage conditions and present users with clear, safe cleanup options. The remediation runs in user context, allowing for interactive popups that guide users through the process while maintaining security and preventing accidental data loss.

Related: What is Ansible? Definition, How It Works & Use Cases

Related: Ansible

Related: How to Disable Windows News and Interests Using Microsoft

Related: How to Expedite Windows Quality Updates Using Microsoft

What Will You Accomplish in This Tutorial?

By following this guide, you'll create a complete automated disk cleanup solution that detects devices with insufficient space for Windows 11 upgrades and guides users through safe cleanup procedures. The solution includes detection logic for storage thresholds, user-friendly remediation popups, and comprehensive monitoring to track success rates across your organization. This proactive approach ensures your Windows 11 upgrade projects proceed smoothly without storage-related failures.

Implementation Guide

Full Procedure

01

Access Intune Proactive Remediations Console

Navigate to the Microsoft Intune admin center to access the Proactive Remediations feature. This is where you'll create and manage your disk cleanup automation.

Open your web browser and go to endpoint.microsoft.com. Sign in with your administrator credentials that have Intune Administrator or Endpoint Security Manager permissions.

Once logged in, navigate to Devices > Endpoint analytics > Proactive remediations. You'll see the main dashboard where existing remediations are listed.

Pro tip: Bookmark the direct URL endpoint.microsoft.com/#view/Microsoft_Intune_Enrollment/UXAnalyticsMenu/~/proactiveRemediations for quick access to this section.

Verification: You should see the Proactive remediations page with options to create new remediations and view existing ones. If you don't see this option, verify your licensing includes Intune Suite features.

02

Create the Detection Script for Low Disk Space

The detection script runs first to identify devices with insufficient disk space for Windows 11 upgrades. This script checks the C: drive and triggers remediation if free space is below the threshold.

Click Create > Proactive remediation. Enter the following details:

  • Name: Disk Cleanup for Win11 Upgrade
  • Description: Detects low disk space and guides users through cleanup for Windows 11 upgrades

In the Detection script section, paste this PowerShell code:

# Detection script for low disk space
$FreeSpaceGB = [math]::Round((Get-WmiObject -Class Win32_LogicalDisk | Where-Object {$_.DeviceID -eq 'C:'}).FreeSpace / 1GB, 2)
$RequiredSpaceGB = 64  # Microsoft recommended minimum for Windows 11

if ($FreeSpaceGB -lt $RequiredSpaceGB) {
    Write-Output "Low disk space detected: $FreeSpaceGB GB free (requires $RequiredSpaceGB GB)"
    exit 1  # Triggers remediation
} else {
    Write-Output "Sufficient disk space: $FreeSpaceGB GB free"
    exit 0  # No remediation needed
}

Set the Run this script using the logged-on credentials to No (runs as SYSTEM for accurate disk space reading).

Warning: Always use exit 1 for detection failures and exit 0 for success. Incorrect exit codes will prevent remediation from triggering.

Verification: The script editor should show no syntax errors, and the detection logic should be clearly visible.

03

Create the User-Friendly Remediation Script

The remediation script provides a user-friendly popup that guides users through cleaning their Recycle Bin and Downloads folder. This approach ensures user consent while automating the cleanup process.

In the Remediation script section, paste this PowerShell code:

# Remediation script with user interaction
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# Get current free space
$FreeSpaceGB = [math]::Round((Get-WmiObject -Class Win32_LogicalDisk | Where-Object {$_.DeviceID -eq 'C:'}).FreeSpace / 1GB, 2)

# Create user-friendly message
$message = @"
Low disk space detected: $FreeSpaceGB GB free

To prepare for Windows 11 upgrade, we recommend cleaning:
• Recycle Bin
• Downloads folder (files older than 30 days)

This will free up space safely. Continue with cleanup?
"@

# Show popup dialog
$result = [System.Windows.Forms.MessageBox]::Show(
    $message, 
    "Disk Cleanup for Windows 11 Upgrade", 
    [System.Windows.Forms.MessageBoxButtons]::YesNo,
    [System.Windows.Forms.MessageBoxIcon]::Information
)

if ($result -eq [System.Windows.Forms.DialogResult]::Yes) {
    try {
        # Empty Recycle Bin
        $shell = New-Object -ComObject Shell.Application
        $recycleBin = $shell.Namespace(0xA)
        $recycleBin.Items() | ForEach-Object { Remove-Item $_.Path -Recurse -Force -ErrorAction SilentlyContinue }
        
        # Clean Downloads folder (files older than 30 days)
        $downloadsPath = "$env:USERPROFILE\Downloads"
        $cutoffDate = (Get-Date).AddDays(-30)
        Get-ChildItem $downloadsPath -Recurse | Where-Object { $_.LastWriteTime -lt $cutoffDate } | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
        
        # Calculate space freed
        $newFreeSpaceGB = [math]::Round((Get-WmiObject -Class Win32_LogicalDisk | Where-Object {$_.DeviceID -eq 'C:'}).FreeSpace / 1GB, 2)
        $spaceFreed = $newFreeSpaceGB - $FreeSpaceGB
        
        Write-Output "Cleanup completed successfully. Freed $spaceFreed GB. New free space: $newFreeSpaceGB GB"
        
        # Show completion message
        [System.Windows.Forms.MessageBox]::Show(
            "Cleanup completed!\n\nSpace freed: $spaceFreed GB\nTotal free space: $newFreeSpaceGB GB",
            "Cleanup Complete",
            [System.Windows.Forms.MessageBoxButtons]::OK,
            [System.Windows.Forms.MessageBoxIcon]::Information
        )
    }
    catch {
        Write-Output "Error during cleanup: $($_.Exception.Message)"
        exit 1
    }
} else {
    Write-Output "User declined cleanup. Manual intervention may be required."
    exit 1
}

Set Run this script using the logged-on credentials to Yes (runs as user for popup interaction and file access).

Pro tip: The script only removes files older than 30 days from Downloads to prevent accidental deletion of recent work files.

Verification: Review the script for proper PowerShell syntax and ensure the user interaction logic is clear.

04

Configure Remediation Settings and Schedule

Configure the execution settings to ensure your remediation runs at optimal intervals without overwhelming users or system resources.

In the Settings section, configure these options:

  • Run frequency: Daily
  • Run remediation script if detection script fails: Yes
  • Enforce script signature check: No (for testing; enable in production if you sign scripts)

For advanced scheduling, you can set specific times:

{
  "schedule": {
    "frequency": "daily",
    "time": "09:00",
    "timezone": "UTC"
  }
}

Configure notification settings:

  • Show notifications to users: No (our script handles user communication)
  • Remediation script timeout: 30 minutes
  • Detection script timeout: 5 minutes
Warning: Don't set the frequency too high (every hour) as this can annoy users with repeated popups if they decline cleanup.

Verification: Ensure all timeout values are reasonable and the schedule aligns with your organization's maintenance windows.

05

Assign the Remediation to Target Groups

Target your remediation to specific device groups, typically those scheduled for Windows 11 upgrades or experiencing storage issues.

Click on the Assignments tab. Here you'll configure which devices receive this remediation:

Add target groups by clicking Add group:

  • Include: Windows 11 Upgrade Pilot Group
  • Include: All Windows 10 Devices (if planning organization-wide upgrade)
  • Exclude: IT Admin Devices (to prevent interruption during critical work)

For testing, start with a small pilot group:

# PowerShell to create test group (run in Azure AD PowerShell)
New-AzureADGroup -DisplayName "Win11-Upgrade-Pilot" -MailEnabled $false -SecurityEnabled $true -MailNickName "Win11Pilot"

Configure assignment filters if needed:

  • Device filter: Operating system version contains "Windows 10"
  • Storage filter: Available storage less than 100 GB
Pro tip: Use dynamic groups based on device properties like OS version or available storage to automatically include relevant devices.

Verification: Review the assignment summary to ensure you're targeting the correct number of devices (typically 10-50 for pilot testing).

06

Deploy and Test the Remediation

Deploy your remediation to the pilot group and verify it works correctly before rolling out organization-wide.

Click Create to save and deploy your remediation. The system will begin distributing it to assigned devices within the next sync cycle (typically 8 hours, or immediately if you force sync).

To force immediate sync for testing, navigate to a test device in Devices > All devices, select the device, and click Sync.

Monitor initial deployment:

# Check Intune Management Extension logs on target device
Get-WinEvent -LogName "Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider/Admin" | Where-Object {$_.Message -like "*Proactive*"} | Select-Object TimeCreated, LevelDisplayName, Message

Test the user experience by manually triggering low disk space on a test device:

# Create temporary large file to simulate low space (run as admin)
$testFile = "C:\temp_space_test.tmp"
fsutil file createnew $testFile 50000000000  # 50GB file
# Remember to delete: Remove-Item $testFile -Force
Warning: Only create test files on dedicated test machines. Never fill up production systems to dangerous levels.

Verification: Check that the detection script identifies low space correctly and the remediation popup appears for users. Monitor the Intune logs for successful execution.

07

Monitor Remediation Success and User Compliance

Use Intune's built-in reporting to track how well your disk cleanup remediation is performing across your device fleet.

Navigate to Devices > Endpoint analytics > Proactive remediations and click on your "Disk Cleanup for Win11 Upgrade" remediation.

Review the key metrics:

  • Detection rate: Percentage of devices where low space was detected
  • Remediation success rate: Percentage where cleanup completed successfully
  • User compliance: How many users accepted vs. declined cleanup

Export detailed reports for analysis:

# PowerShell to export remediation data via Graph API
$headers = @{
    'Authorization' = "Bearer $accessToken"
    'Content-Type' = 'application/json'
}

$uri = "https://graph.microsoft.com/beta/deviceManagement/deviceHealthScripts/{scriptId}/deviceRunStates"
$response = Invoke-RestMethod -Uri $uri -Headers $headers -Method Get
$response.value | Export-Csv -Path "remediation-results.csv" -NoTypeInformation

Set up automated alerting for failures:

  • Success threshold: Alert if success rate drops below 80%
  • Detection threshold: Alert if more than 30% of devices show low space
Pro tip: Create a Power BI dashboard connecting to the Intune data warehouse for real-time monitoring of your Windows 11 upgrade readiness.

Verification: Confirm that you can see device-level results, including which users accepted cleanup and how much space was freed on each device.

08

Optimize and Scale the Remediation

Based on pilot results, refine your remediation script and expand deployment to your entire organization preparing for Windows 11 upgrades.

Analyze common patterns from your pilot data:

  • Average space freed: Adjust thresholds if cleanup isn't freeing enough space
  • User decline rate: If high, consider making cleanup more automated or improving messaging
  • Failure patterns: Identify devices where remediation consistently fails

Enhanced version with additional cleanup targets:

# Enhanced remediation script with more cleanup options
# Add to existing remediation script before the cleanup section

# Additional cleanup targets
$tempFolders = @(
    "$env:TEMP",
    "$env:LOCALAPPDATA\Temp",
    "C:\Windows\Temp"
)

# Clean temporary files older than 7 days
foreach ($folder in $tempFolders) {
    if (Test-Path $folder) {
        Get-ChildItem $folder -Recurse -File | Where-Object {
            $_.LastWriteTime -lt (Get-Date).AddDays(-7)
        } | Remove-Item -Force -ErrorAction SilentlyContinue
    }
}

# Clean Windows Update cache if safe
$updateCache = "C:\Windows\SoftwareDistribution\Download"
if ((Get-Service wuauserv).Status -eq 'Stopped') {
    Remove-Item "$updateCache\*" -Recurse -Force -ErrorAction SilentlyContinue
}

Scale to production by updating assignments:

  • Remove pilot restrictions
  • Add "All Windows Devices" group
  • Implement staged rollout (10% per week)
Warning: Before scaling, ensure your help desk is prepared for user questions about the cleanup popups and process.

Verification: Monitor the expanded deployment for any performance issues or unexpected failures. Confirm that Windows 11 upgrade success rates improve in devices that received cleanup.

Frequently Asked Questions

What are the licensing requirements for Intune Proactive Remediations?+
Intune Proactive Remediations requires a Microsoft Intune license, which is included in Microsoft 365 E3/E5 or Enterprise Mobility + Security E3/E5 plans. Some advanced features may require the Intune Suite add-on. You can verify your licensing in the Intune admin center under Tenant administration > Licenses.
How often should the disk cleanup remediation run for Windows 11 upgrades?+
For Windows 11 upgrade preparation, running the remediation daily is recommended during the weeks leading up to your upgrade deployment. This ensures devices maintain adequate free space as users continue working. You can reduce frequency to weekly after upgrades are complete for ongoing maintenance.
Can users bypass or disable the disk cleanup remediation?+
Users can decline the cleanup when prompted by the popup, but they cannot disable the remediation entirely. The script will continue to detect low disk space and prompt again on the next scheduled run. For persistent non-compliance, consider implementing a more automated cleanup approach or escalating to IT support.
What happens if the remediation script fails to run on a device?+
Failed remediations are logged in the Intune Management Extension logs on the device and reported in the Intune admin center. Common causes include PowerShell execution policy restrictions, user not logged in during remediation, or insufficient permissions. The script will retry on the next scheduled execution cycle.
How much disk space can typically be freed using this remediation approach?+
Results vary significantly by user behavior, but typical cleanup of Recycle Bin, Downloads folder, and temporary files can free 5-20GB per device. Power users with large download folders or those who rarely empty their Recycle Bin may see much higher space recovery. The script provides feedback on actual space freed for monitoring purposes.

Discussion

Share your thoughts and insights

Sign in to join the discussion