So I posted a couple of weeks ago that I discovered a project I could do with PowerShell and some sort of automation. Well I'd like to debut my first public script, Clean-WindowsUpdates.
As I've mentioned previously, this is more of a project to help me learn PS and if it helps someone else, all the better. I'm sure there are better scripts out there to accomplish the same or similar results but this is for my learning experience. :)
So what does this script do? It performs the following -
- Check for Administrator Rights
- Define a registry key and property using the New-ItemProperty cmdlet
- Use a Try/Catch/Finally block
- Start the Cleanup Wizard using the Start-Process cmdlet
- Perform a cleanup task
The goal of this script is to safely remove superseded Windows Updates from the CBS store. There have been plenty of ways to do this in an unsupported fashion for Windows 7, but now since KB2852386 was released back in October 2013 we can use the functionality in the Windows Cleanup Wizard.
I've released the script here. There are several features I'd like to add such as the detection of the Windows version and whether leveraging Windows Cleanup Wizard is used or if DISM would be appropriate.
Removes Windows Updates using the Microsoft supported Disk Cleanup Wizard
This script will use the Microsoft supported Disk Cleanup Wizard plugin to
safely remove applied Windows updates from the system. Once removed, these
updates cannot be uninstalled. The primary benefit is recovering disk space.
Write-Verbose "Checking for Administrator rights."
$Identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$Principal = new-object Security.Principal.WindowsPrincipal $Identity
If ($Principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -eq $False)
Write-Verbose "Script isn't running with Administrator rights. Exiting."
Write-Verbose "Check if the required registry key exists."
$Key = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Update Cleanup"
Write-Verbose "Writing the registry configuration for the Cleanup function."
New-ItemProperty -Path $Key -Name StateFlags0128 -PropertyType DWord -Value 2 -ErrorAction Stop | Out-Null
Write-Verbose "Couldn't write the registry key needed for the Cleanup function."
Write-Verbose "A general error occured, exiting."
Write-Verbose "Executing the Cleanup Manager."
Start-Process CleanMgr.exe -ArgumentList "/sagerun:128" -NoNewWindow -Wait
Write-Verbose "Cleaning up registry configuration for the Cleanup function."
Remove-ItemProperty -Path $Key -Name StateFlags0128