For years, I've used a scrip to fire off cleanmgr.exe and run through the typical job referenced/saved in the registry. It has generally worked pretty well however, lately, it has been failing. When I jump into the machine and run the Disk Cleanup GUI and select all the boxes, it runs fine but, not until I handle a nag window that sates the following:
If you clean up the previous Windows installations or temporary installation files, you will no longer be able to restore the machine back to the previous version of Windows. Are you sure that you want to do this?
My question is this: How do I get beyond that nag window in code? As near as I can tell, it's the only reason my scripted job doesn't work. The following is the code I use to populate the registry entry that cleanmgr.exe can later reference. Again, as near as I can tell, it worked for years.
<#
This is a quick & dirty way to be able to run Windows Disk Cleanup in the background.
This is basically the same as running the following command which allows you to tweak the settings and save them to the Registry.
cleanmgr.exe /sageset:13
The aforementioned command tweaks the already existing reg-keys by adding the "StateFlags0013" Dword entry to them.
The code "mimics" this so that we can later call cleanmgr.exe - silently - from within our RMM CMD session or scheduled task.
Once the reg-tweaks are done, you can run the following command to clean up space on the drive.
cleanmgr.exe /sagerun:13
#>
Where all the reg-keys live.
$RegPathRoot = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
$StateFlag = "StateFlags0013"
Array for the individual reg-keys.
$RegKeys = @(
"Active Setup Temp Folders",
"BranchCache",
"D3D Shader Cache",
"Delivery Optimization Files",
"Diagnostic Data Viewer database files",
"Downloaded Program Files",
"Feedback Hub Archive log files",
"Internet Cache Files",
"Language Pack",
"Old ChkDsk Files",
"Previous Installations",
"Recycle Bin",
"RetailDemo Offline Content",
"Setup Log Files",
"System error memory dump files",
"System error minidump files",
"Temporary Files",
"Thumbnail Cache",
"Update Cleanup",
"User file versions",
"Windows Defender",
"Windows Error Reporting Files",
"Windows Upgrade Log Files"
)
Tweak the registry
ForEach ($RegKey in @($RegKeys)) {
New-ItemProperty -Path "$RegPathRoot$($RegKey)" -Name "$StateFlag" -Value "2" -PropertyType "DWord" -Force -ErrorAction SilentlyContinue
}
Update
I ran this on my test VM today and it worked. I loaded up Win11 23H2, upgraded to 24H2, ran my reg-tweak script above, and then kicked off cleanmgr.exe /sagerun:13. I was never prompted with the aforementioned popup even though I somehow ended up with two different little GUI windows at one point. (Not sure where the second one came from.) I'm assuming any windows are hidden when the job is kicked off via our RMM. Regardless, the job still worked. This may just be an odd issue with some of our machines.