Hello Sokoban,
You can try with the following script and deploy it as a configuration item or baseline:
$now = Get-Date
$writeTime = $now.AddDays(-21)
$CMObject = New-Object -ComObject "UIResource.UIResourceMgr"
$CMCacheObjects = $CMObject.GetCacheInfo()
$CMCacheElements = $CMCacheObjects.GetCacheElements()
$CMCacheElements | Where {$_.LastReferenceTime -le $writeTime} | ForEach-Object {$CMCacheObjects.DeleteCacheElement($_.CacheElementID)}
$FilePath = "C:\Windows\ccmcache"
Get-ChildItem -Path $FilePath -recurse | Where {($_.LastAccessTime -le $writeTime) -and ($_.PSISContainer) -eq $false} | Remove-Item -Recurse -Force
do {
$CountDir = Get-ChildItem -path $FilePath -recurse | Where {($_.LastAccessTime -le $writeTime) -and ($_.PSISContainer -eq $true) -and ($_ | Get-ChildItem).Count -eq 0}
$CountDir | Remove-Item -Recurse -Force
$i++
} While (($i -lt 100) -and ($CountDir.count -gt 0))
This will delete all content older than 21 days.
Regards,
Youssef Saad | Blog: https://youssef-saad.blogspot.com/ | LinkedIn