Tuesday, June 16, 2009

VBScript: Remove old Windows Updates

My virtual machines regularly fill up their system disks, with old uninstall information. I was getting tired of fixing this manually, so I wanted to create a script to do this automatically. I found a script that removed all updates and modified it to only remove updates older than 90 days:


Option Explicit
Dim o, oShell, nConfirm
Set o = WScript.Application
o.Interactive = True
Set oShell = CreateObject("WScript.Shell")
nConfirm = oShell.Popup("Do you want to remove Windows Update Uninstall Files?", 0, "Remove Windows Update Uninstall Files", 4 + 32)
If nConfirm = 7 Then
o.Quit 0
End If
Dim oFSO, sWinDir, oFolder, oDictionary, oSubFolder, sFolderName, sFolderPath, sUpdateName, sDeleted, sFolderDate
Set oFSO = CreateObject("Scripting.FileSystemObject")
sWinDir = oFSO.GetSpecialFolder(0)
sDeleted = vbNullString
Set oFolder = oFSO.GetFolder(sWinDir)
Set oDictionary = CreateObject("Scripting.Dictionary")
For Each oSubFolder In oFolder.SubFolders
sFolderName = LCase(oSubFolder.Name)
sFolderPath = LCase(oSubFolder.Path)
'Check date of update
sFolderDate = oSubFolder.DateCreated
If Left(sFolderName, 12) = "$ntuninstall" And Mid(sFolderName, 13, 2) = "kb" Or Mid(sFolderName, 13, 2) = "q" Then
sUpdateName = Mid(sFolderName, 13, Len(sFolderName) - 13)
'Remove update if older than x days
If DateDiff("d", sFolderDate, Now) > 90 Then
oDictionary.Add sUpdateName, sFolderPath
End If
End If
Next
For Each sUpdateName in oDictionary.Keys
sDeleted = sDeleted & vbCrLF & sUpdateName
sFolderPath = oDictionary.Item(sUpdateName)
On Error Resume Next
oShell.RegDelete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" & sUpdateName & "\"
On Error Goto 0
oShell.Run "%ComSpec% /C RD /S /Q " & Chr(34) & sFolderPath & Chr(34), 0, True
Next
If Len(sDeleted) > 0 Then
WScript.Echo "The uninstall data for the following updates are now removed:" & vbCrLf & UCase(sDeleted), vbOKOnly
sDeleted = vbNullString
Else
WScript.Echo "No Windows Update Folders found for removal", vbOKOnly + vbInformation, "Nothing To Do"
End If
o.Quit 0

Save this code as removeOldUpdates.vbs and schedule a task to run weekly.

I'm thinking about expanding this script to clean up all kinds of temporary files.

No comments: