While using MDT to remaster an existing Windows 7 image I added tasks to apply Windows 7 Service Pack 1 and a slew of other updates to the image (so that deployed workstations are up to date out of the gate instead of waiting for updates to come down to each system across the network). Unfortunately this bloated the end product WIM by almost 2 GB. I started to look into ways I could cleanup any unnecessary files on the hard drive before capturing the image. Instead of just hacking away at the disk, deleting temporary files and other caches, I decided to try to integrate the built-in Disk Cleanup utility.
Disk Cleanup, cleanmgr.exe, has command line parameters that are well documented but there is little to nothing on how to automate this, especially in the context of a MDT task sequence. The typical process is to run cleanmgr.exe /sageset:n (where n is an arbitrary integer) and set the files to delete in the interface. This then configures a cleanup profile in the registry so that when running cleanmgr.exe /sagerun:n it has a preset configuration to use.
To automate this for the task sequence I made the decision that every cache type (aka handler) is to be deleted in this scenario, including the one most important to me: Service Pack Backup Files. I wrote the attached MDT-style script that loops through each subkey under HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches and sets the StateFlags0042 value to DWORD 2 (in this example, n = 42). There is an article on MSDN that includes an excellent description of the StateFlags value. The script then runs cleanmgr.exe /sagerun:42 to do the needful.
I added this cleanup task to the end of the Custom Tasks group of the State Restore phase (for those of you using the Standard Client Task Sequence). It cleaned almost 3 GB of data from the system, which resulted in the final WIM only growing by 575 MB from the starting custom image (instead of almost 2 GB without the cleanup).