I agree with the intent of using Remediation instead to detect and clean up.
Here is an example of what I have recently setup. Use at your own risk!
Detection script for less than 30GB
$MinimumThreshold = 30GB
$FreeSpace = (Get-Volume -DriveLetter ($env:SystemDrive -replace ":")).SizeRemaining
if($FreeSpace -lt $MinimumThreshold){
exit 1
}else{
exit 0
}
Remediation script to clear Configuration Manager Cache, run Disk Cleanup and clean up temp directories.
## 1. Clean out Configuration Manager Cache Directory ##
[__comobject]$CCMComObject = New-Object -ComObject 'UIResource.UIResourceMgr'
$CacheInfo = $CCMComObject.GetCacheInfo().GetCacheElements()
ForEach ($CacheItem in $CacheInfo) {
$null = $CCMComObject.GetCacheInfo().DeleteCacheElement([string]$($CacheItem.CacheElementID))
}
## 2. Run Disk Clean-up with selection actions ##
$CleanupSelection = @('Temporary Files','System error minidump files','System error memory dump files','Recycle Bin','Device Driver Packages','Windows Error Reporting Files')
Foreach ($KeyName in $CleanupSelection) {
$NewItemParams = @{
Path = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\$KeyName"
Name = 'StateFlags0001'
Value = 1
PropertyType = 'DWord'
ErrorAction = 'SilentlyContinue'
}
New-ItemProperty @NewItemParams -Force | Out-Null
}
$CleanMgr = Start-Process -FilePath CleanMgr.exe -ArgumentList '/sagerun:1' -NoNewWindow -PassThru
$CleanMgr | Wait-Process -Timeout 300 -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
## 3. Clean out Temp Directory and Recycling Manually ##
Remove-Item -path "$Env:Windir\TEMP\*" -Recurse -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
Remove-Item -path "$Env:SystemDrive\`$Recycle.Bin" -Recurse -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue