Windows 10

Automating Disk Cleanup on Windows 10

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

4 replies »

  1. So when running this, did you have any issue with it affecting the way your system run?

    Meaning, Windows 10 issues after.

    I run certain software suit & VMware for automation use & am wondering if this would affect that.

    Or was your test just under an controlled environment that you didn’t care if a bug was created?

    Thanks for your timw


    • I wouldn’t expect this to cause any issues, since Windows will periodically run it automatically too. It’s really just cleaning up random logs, temp folders, and other “known cruft.” It’s not doing anything aggressive (compared to other third-party tools that can get a little too aggressive).