Jump to content

Automate the Disk Cleanup tool


Jon
 Share

Recommended Posts

  • Administrators

When creating my OS master image as the last step I run the Disk Cleanup tool to get rid of the old versions of Windows Update files and temp files created during the build. On Windows 10 this also can be used to cleanup the 100MB of "Retail Demo Content" that is present >_<

Microsoft Support has this article on how to automate Disk Cleanup. It's not as simple as adding some command-line switches. You have to manually run it once with /sageset:nn, then select the items you want to clean. This creates some registry keys and thereafter you can run it with /sagerun:nn (where nn is the same number) and it will clean those items. Not ideal when you want to run it as a "one-off".

This PowerShell script automatically creates all the relevant registry keys, runs Disk Cleanup, then deletes the keys.

<#
.SYNOPSIS
Automates the Disk Clean tool to clean up all possible items for the given OS.
#>


# V2 admin check
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
    Write-Warning "Please run this script as an Administrator!"
    Exit 1
}

# Create reg keys
$volumeCaches = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
foreach($key in $volumeCaches)
{
    New-ItemProperty -Path "$($key.PSPath)" -Name StateFlags0099 -Value 2 -Type DWORD -Force | Out-Null
}

# Run Disk Cleanup 
Start-Process -Wait "$env:SystemRoot\System32\cleanmgr.exe" -ArgumentList "/sagerun:99"

# Delete the keys
$volumeCaches = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
foreach($key in $volumeCaches)
{
    Remove-ItemProperty -Path "$($key.PSPath)" -Name StateFlags0099 -Force | Out-Null
}

 

Link to comment
Share on other sites

  • Administrators

Seems to be working here and it's not visible in optional features. It's not come back yet on the images I've been doing. Maybe it's because I run the script as System during ConfigMgr OSD and it nukes it early :) 

Link to comment
Share on other sites

Nice code Jon.

Out of interest of sharing, I did this quite some time back about a query about the Disk Cleanup Tool (DCT) and never got to share. Link to a HTA file based on Microsoft documentation (not mine, just my altered DCT for dummies). I use Disk Cleanup Tool for my log off script script event so it has|is been useful. It (DCT) can be programmed. Examples are CMD as PS. arrrgh fails setting workingdir with [] in the path to the script.

Regards to old friends.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...