I’ve seen a variety of blogs over the years that talk about how to do this, but I never took the time to actually try it myself. No time like the present. It turns out that the process is fairly simple: Set registry values to say what you want to clean up and then launch CLEANMGR.EXE with the right command line options. Since I wanted to put this into an MDT task sequence, I also wanted to wait until the process was done.
The bulk of the work for this was amazingly already documented by Microsoft. Combine that documentation with some sample PowerShell scripts on StackOverflow and you can see where my script was derived, I just simplified it a little:
Get-ChildItem -Path ‘HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches’ | New-ItemProperty -Name StateFlags001 -Value 2 -PropertyType DWORD
Start-Process -FilePath CleanMgr.exe -ArgumentList ‘/sagerun:1’ -WindowStyle Hidden -Wait
Get-Process -Name cleanmgr,dismhost -ErrorAction SilentlyContinue | Wait-Process -Timeout 900
(This is a three-line script, so if you copy it, make sure the first line doesn’t have a break in it.) To run that script from MDT, copy the script into your deployment share’s “Scripts” folder and set up a “Run PowerShell script” step:
The script enables every cleanup item possible (line #1), starts CLEANMGR.EXE (line #2), then waits for separate CLEANMGR.EXE and DISMHOST.EXE processes to complete before exiting. I added the 15-minute (900 second) timeout because when I ran the script to test it on my server, the processes never ended, so it’s good to give up at some point.
Now, whether it does much good during the image creation process is a separate debate. It might free up a small amount of space; don’t expect miracles.
Categories: Windows 10