The Deep Clean: Automating Server Disk Space Triage

Automate server disk space recovery with this aggressive PowerShell triage script. Learn how to safely purge corrupted CBS logs, fix the MakeCab temp folder bug, and properly reduce the WinSxS Component Store using DISM.

The Deep Clean: Automating Server Disk Space Triage

6 min. read


The Ticket: The Midnight Storage Crisis

A critical SQL server throws a 2 AM monitoring alert. The C: drive just dropped to 0 bytes free. The database engine has halted, VSS writers are failing so backups are completely dead, and the client's ERP software is offline. You log in via your RMM background terminal and see that the culprit is not database growth or user data. The drive is choked by a massive buildup of Component-Based Servicing logs, orphaned Windows Update temp files, and a bloated WinSxS folder. We need a script to safely purge this system garbage and restore server functionality instantly.


Pre-Flight Check

  • Permissions: Local Administrator or NT AUTHORITY\SYSTEM (via RMM).
  • Tools: PowerShell 5.1+.
  • Impact: Moderate. While deleting temp files is instant and safe, the DISM component cleanup phase will spike CPU and disk I/O heavily for up to 20 minutes.
[!WARNING] The Risk Factor: Never attempt to manually delete files inside the C:\Windows\WinSxS folder. Doing so will irreparably corrupt the Windows operating system. Always use the built-in Dism.exe tool to manage this directory.

The Solution: The Triage Script

Standard disk cleanup utilities require GUI interaction and often miss the largest offending files. Deploy this PowerShell script via your RMM to aggressively but safely target the known pain points.

PowerShell

# --- 404 & More: Automated Disk Space Triage ---

# 1. Admin Rights Check
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Error "CRITICAL ERROR: Execution halted. Elevated privileges required."
    exit 1
}

Write-Host "Initiating Deep Clean..."

# 2. Stop the Windows Update Service to unlock orphaned files
Write-Host "Stopping wuauserv to release file locks..."
Stop-Service -Name wuauserv -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 5

# 3. Purge orphaned CBS Persist Logs and CAB files
Write-Host "Clearing archived CBS logs..."
$CBSPath = "$env:windir\Logs\CBS"
Get-ChildItem -Path $CBSPath -Include "CbsPersist_*.log", "*.cab" -Recurse -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue

# 4. Clear Windows Temp (Targeting the MakeCab bug)
Write-Host "Purging C:\Windows\Temp..."
$WinTemp = "$env:windir\Temp"
Get-ChildItem -Path $WinTemp -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-1) } | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue

# 5. Clear User Temp Profiles
Write-Host "Purging User Temp directories..."
$UserProfiles = Get-ChildItem -Path "C:\Users" -Directory
foreach ($Profile in $UserProfiles) {
    $UserTemp = "$($Profile.FullName)\AppData\Local\Temp"
    if (Test-Path $UserTemp) {
        Get-ChildItem -Path $UserTemp -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-1) } | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
    }
}

# 6. Restart Windows Update
Start-Service -Name wuauserv -ErrorAction SilentlyContinue

# 7. Run Component Store Cleanup
Write-Host "Executing DISM Component Cleanup (This may take 15+ minutes)..."
Start-Process -FilePath "Dism.exe" -ArgumentList "/online /Cleanup-Image /StartComponentCleanup" -Wait -NoNewWindow

Write-Host "SUCCESS: Triage complete. Verify free space." -ForegroundColor Green

The "Why" (Root Cause)

Why does C:\Windows\Temp suddenly fill up with hundreds of gigabytes of data? The culprit is usually the infamous makecab.exe bug.

Windows constantly generates Component-Based Servicing (CBS) logs in C:\Windows\Logs\CBS. When the active cbs.log file reaches 50MB, the OS renames it to CbsPersist_[timestamp].log and attempts to compress it into a .cab file using the makecab.exe process. If the log file is locked by another process or grows too large (often over 2GB), the compression fails. The OS gets stuck in a loop, continually generating temporary cab_XXXX files in C:\Windows\Temp until the entire hard drive hits zero bytes.

By aggressively targeting the CbsPersist archives and the Windows Temp directory, we break this compression loop and instantly reclaim the lost storage.


Under the Hood (Technical Deep Dive)

The final step of the script utilizes the Deployment Image Servicing and Management (DISM) tool. To understand why this is necessary, you have to look at the WinSxS (Windows Side-by-Side) folder.

When Windows installs an update, it does not just overwrite the old system files. It keeps the previous versions in the WinSxS folder to allow for update rollbacks. However, looking at the file properties in Windows Explorer is highly deceptive. Microsoft uses "Hard Links" for this directory. A hard link means multiple file paths point to the exact same block of data on the physical disk. Explorer counts the file size twice, making WinSxS look much larger than it actually is.

Even with hard links, superseded updates (updates that have been replaced by newer cumulative patches) eventually bloat the drive. The /StartComponentCleanup command tells the OS to analyze the Component Store, identify packages that have been superseded for more than 30 days, and physically delete the obsolete binaries.


RMM & Automation Tips

  • The Self-Healing Monitor: Do not run this script as a blind weekly task. The DISM cleanup is too resource-intensive. Tie this script to a specific RMM monitor. Set the trigger for "System Drive Free Space < 10%". When the alarm trips, the RMM fires the script automatically, often resolving the issue before a human engineer even opens the ticket.
  • Volume Shadow Copies: Sometimes "missing" disk space is hiding in the System Volume Information folder due to bloated VSS snapshots. If the triage script completes but the drive is still full, execute vssadmin list shadowstorage via your RMM terminal to see if your backup agent forgot to prune its old snapshots.

Troubleshooting & Edge Cases

  • Edge Case 1: DISM Hangs at 20%. If the DISM command freezes indefinitely, the Component Store itself is corrupted. You will need to interrupt the script and run Dism.exe /online /Cleanup-Image /RestoreHealth to repair the image manifest before attempting the cleanup again.
  • Edge Case 2: Locked Temp Files. Some files in C:\Windows\Temp are actively locked by third-party antivirus definitions or print spooler metadata. The script uses -ErrorAction SilentlyContinue to gracefully skip these locked files. Do not force-kill random processes to delete 5KB text files; focus on the massive CAB archives.