The Amazing Disk Space Notifier

In today’s digital workplace, efficient disk space management is crucial for maintaining optimal performance and productivity on Windows devices. While Microsoft Intune offers various configuration profiles to manage storage, savvy IT professionals are turning to more dynamic and customizable solutions. Enter the power of remediation scripts – a game-changing approach to automated disk space management.

disk space saver intune

This comprehensive guide will walk you through the process of creating and deploying a robust disk space management solution using Microsoft Intune and PowerShell scripting. We’ll explore how this method surpasses traditional configuration profiles, offering greater flexibility and control over your endpoints’ storage health.

Key topics we’ll cover:

  • The limitations of standard Intune configuration profiles for disk management
  • Benefits of using remediation scripts for automated disk cleanup
  • Step-by-step guide to creating an effective disk space management script
  • Best practices for deploying and monitoring your solution through Intune
  • Real-world scenarios and performance improvements

Whether you’re an IT administrator looking to streamline operations or a business owner concerned about device performance, this guide will equip you with the knowledge to implement a cutting-edge disk space management strategy. Let’s dive in and discover how to leverage Intune and PowerShell to keep your Windows devices running smoothly and efficiently.

Space Invaders: Identifying Top Disk Space Consumers on Windows Devices

Understanding what consumes space on Windows machines is crucial for effective disk management. The usual suspects include temporary files, which accumulate from various applications and system processes over time. Another significant contributor is OneDrive, especially when files are not optimized for cloud storage. The concept of file dehydration, where online-only files are stored locally, can lead to unexpected space usage. Other space-hungry culprits include outdated Windows update files, bloated user profiles, and redundant application data.

Beyond these common offenders, several other elements can silently eat away at your disk space. The Windows page file, used for virtual memory management, can grow substantially over time. Old system restore points and shadow copies, while useful for recovery, can consume significant space if left unchecked. Browser caches from multiple web browsers can accumulate rapidly, especially for users who frequently visit media-rich websites. Additionally, forgotten downloads, duplicate files, and unused language packs can clutter your system. For developers and power users, Docker images and virtual machine files can be major space hogs. By identifying these space invaders, we can target our automated cleanup efforts more effectively, ensuring optimal disk performance across your managed devices.

Storage Sense: Windows’ Built-in Data Guardian and Its Limitations

Storage Sense is Windows 10 and 11’s built-in solution for automatic disk space management. This feature, when enabled, works silently in the background to help keep your device running smoothly by freeing up space automatically. Here’s a detailed look at what Storage Sense offers:

  1. Automatic Cleanup: Storage Sense can automatically delete temporary files, empty the Recycle Bin, and remove files from your Downloads folder that haven’t been opened for a specified period.
  2. Customizable Settings: Users can configure Storage Sense to run during low disk space situations or on a schedule (daily, weekly, or monthly).
  3. OneDrive Integration: For OneDrive users, Storage Sense can automatically change files that haven’t been opened in a while to online-only files, freeing up local space while keeping files accessible in the cloud.
  4. Windows Update Cleanup: It can remove old Windows update files to reclaim space after system updates.
  5. App Management: Storage Sense can remove unnecessary files from apps and remove apps that you don’t use to free up space.
  6. Hibernation File Management: In some cases, it can reduce the size of the hibernation file to save space.
  7. User Control: While automatic, users can manually trigger Storage Sense to run at any time.
  8. Temporary Files Handling: It intelligently manages various types of temporary files, including those from apps, previous Windows installations, and the Delivery Optimization feature.

However, Storage Sense has limitations:

  1. Limited Customization: While it offers some settings, it lacks fine-grained control over what gets deleted and when.
  2. No Reporting: It doesn’t provide detailed reports on what space was freed and from where.
  3. Lack of Centralized Management: In enterprise environments, there’s no centralized way to manage Storage Sense across multiple devices.
  4. Conservative Approach: To avoid accidentally deleting important files, Storage Sense tends to be conservative in its cleanup, potentially missing opportunities for more aggressive space saving.

While Storage Sense is a valuable built-in tool for basic disk space management, its limitations highlight the need for more robust, customizable solutions in enterprise environments. This is where custom scripts deployed through Intune can provide a more powerful and flexible approach to disk space management.

Beyond Storage Sense: Crafting a Robust Disk Space Management Script with PowerShell and Intune

While Storage Sense offers a basic solution for disk space management, enterprise environments often require a more comprehensive and customizable approach. By leveraging PowerShell and Intune, we can create a powerful script that not only addresses immediate space concerns but also implements proactive measures for long-term disk health.

Our script will perform the following key actions:

  1. Check available drive space
  2. If space is below 10GB, prompt the user to delete unnecessary items
  3. Enable and configure Storage Sense for automatic cleanup

In addition to these core functions, we can enhance our script with the following space-saving actions:

  1. Clear browser caches for multiple browsers (Edge, Chrome, Firefox)
  2. Remove old Windows Update files and previous Windows installations
  3. Delete temporary files from user and system directories
  4. Clear the Recycle Bin
  5. Remove old system restore points, keeping only the most recent
  6. Uninstall specified unused applications
  7. Compress old, rarely accessed files
  8. Identify and list large files for user review
  9. Remove old log files
  10. Clean up Windows Component Store (WinSxS folder)

By incorporating these additional actions, our script becomes a comprehensive disk space management solution. This approach allows for greater control and customization compared to built-in tools, making it ideal for diverse enterprise environments with varying needs.

In the next section, we’ll dive into the PowerShell code that brings this robust disk space management solution to life, ready for deployment via Microsoft Intune.

Detection Script

# Start transcript for logging
Start-Transcript -Path "C:\ProgramData\Microsoft\IntuneManagementExtension\Logs\DiskSpaceDetection.log" -Append

Write-Host "Starting disk space detection script..."

try {
    # Get all fixed drives
    $drives = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 }
    
    Write-Host "Found $($drives.Count) fixed drives."

    $lowSpaceDrives = @()

    foreach ($drive in $drives) {
        $freeSpaceGB = [math]::Round($drive.FreeSpace / 1GB, 2)
        Write-Host "Drive $($drive.DeviceID) has $freeSpaceGB GB free space."
        
        if ($freeSpaceGB -lt 10) {
            $lowSpaceDrives += $drive.DeviceID
            Write-Host "Drive $($drive.DeviceID) has less than 10 GB free space. Adding to low space drives list."
        }
    }

    if ($lowSpaceDrives.Count -gt 0) {
        Write-Host "Detected $($lowSpaceDrives.Count) drives with less than 10 GB free space."
        Write-Host "Low space drives: $($lowSpaceDrives -join ', ')"
        Write-Output "Remediation needed"
        Exit 1
    } else {
        Write-Host "All drives have more than 10 GB free space."
        Write-Output "No remediation needed"
        Exit 0
    }
}
catch {
    $errorMessage = $_.Exception.Message
    Write-Host "Error occurred: $errorMessage"
    Write-Error $errorMessage
    Exit 1
}
finally {
    Stop-Transcript
}

This script does the following:

  1. Starts a transcript for logging, saving it in the IntuneLogs folder in ProgramData.
  2. Uses Get-WmiObject to find all fixed drives on the system.
  3. Checks each drive’s free space, converting it to GB for easier reading.
  4. If any drive has less than 10 GB free space, it’s added to a list of low space drives.
  5. If there are any drives with low space, it outputs “Remediation needed” and exits with code 1, triggering the remediation script.
  6. If all drives have sufficient space, it outputs “No remediation needed” and exits with code 0.
  7. Uses Write-Host throughout to provide detailed information about what the script is doing.
  8. Catches any errors, logs them, and exits with code 1 if an error occurs.
  9. Stops the transcript in the finally block to ensure logging is completed even if an error occurs.

Remediation Script

# Start transcript for logging
Start-Transcript -Path "C:\ProgramData\Microsoft\IntuneManagementExtension\Logs\DiskSpaceRemediation.log" -Append

Write-Host "Starting disk space remediation script..."

try {
    # Get all fixed drives with less than 10 GB free space
    $lowSpaceDrives = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 -and ($_.FreeSpace / 1GB) -lt 10 }
    
    Write-Host "Found $($lowSpaceDrives.Count) drives with less than 10 GB free space."

    if ($lowSpaceDrives.Count -gt 0) {
        # Prepare the message for the toast notification
        $driveList = $lowSpaceDrives | ForEach-Object { "$($_.DeviceID) ($('{0:N2}' -f ($_.FreeSpace / 1GB)) GB free)" }
        $message = "The following drives have less than 10 GB of free space:`n" + ($driveList -join "`n") + "`n`nPlease delete unnecessary files to free up space."

        Write-Host "Preparing toast notification with message: $message"

        # Load necessary assemblies for toast notifications
        [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
        [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null

        # Prepare the toast notification XML
        $toastXml = [Windows.Data.Xml.Dom.XmlDocument]::new()
        $toastXml.LoadXml(@"
        <toast>
            <visual>
                <binding template="ToastText02">
                    <text id="1">Low Disk Space Warning</text>
                    <text id="2">Your computer's storage is running low. Please delete old or unused files to free up space. This will help keep your system running smoothly. If you need assistance, contact the IT helpdesk.</text>
                </binding>
            </visual>
        </toast>
"@)

        # Create and show the toast notification
        $toast = [Windows.UI.Notifications.ToastNotification]::new($toastXml)
        [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("Disk Space Alert").Show($toast)

        Write-Host "Toast notification sent to user."

        # Enable Storage Sense
        Write-Host "Enabling Storage Sense..."
        if (Get-Command "Enable-StorageSense" -ErrorAction SilentlyContinue) {
            Enable-StorageSense
            Write-Host "Storage Sense enabled successfully."
        } else {
            Write-Host "Enable-StorageSense command not available. Setting registry key instead."
            New-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\StorageSense\Parameters\StoragePolicy" -Name "01" -Value 1 -PropertyType DWORD -Force
        }

        Write-Host "Remediation actions completed."
    } else {
        Write-Host "No drives with less than 10 GB free space found. This is unexpected as the detection script triggered remediation."
    }

    Exit 0
}
catch {
    $errorMessage = $_.Exception.Message
    Write-Host "Error occurred: $errorMessage"
    Write-Error $errorMessage
    Exit 1
}
finally {
    Stop-Transcript
}

The final step is to deploy the above script to our devices using Remediations. Check the following posts for learning how to deploy an Intune remediation script:

References and documentation:

Leave a Reply

Your email address will not be published. Required fields are marked *