merge previous cleanup scripts into one Start-Cleanup.ps1 script

This commit is contained in:
2026-10-22 16:58:12 -04:00
parent c8eec20391
commit e9fcc2f33b
4 changed files with 1493 additions and 0 deletions
+737
View File
@@ -0,0 +1,737 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Retention-aware cleanup for Windows workstations and servers.
.DESCRIPTION
Reads Cleanup* variables from the calling scope (including the RMM Run-Script
dot-source scope). Missing variables use Get-SystemCleanupDefaults. No param()
block deliberately: RMM variables must not be overwritten by parameter defaults.
ReportOnly defaults to true and assesses enabled and disabled categories separately.
Server exclusions still apply. See rmm/Start-SystemCleanup.ps1 and
docs/SystemCleanup.md for options, server exclusions, and legacy operation mapping.
The core is self-contained; loading Tools.ps1 is the RMM shim's responsibility.
#>
function Get-SystemCleanupDefaults {
return [ordered]@{
CleanupReportOnly = $true
CleanupTempDays = 7
CleanupDiagnosticDays = 30
CleanupBackupDays = 30
CleanupSystemTemp = $true
CleanupUserTemp = $true
CleanupServiceTemp = $true
CleanupCBSArchives = $true
CleanupActiveCBSLog = $false
CleanupCrashDumps = $true
CleanupWERArchives = $true
CleanupAutodeskInstallers = $false
CleanupRecycleBin = $false
CleanupDisableHibernation = $false
CleanupCompactSearch = $false
CleanupShadowCopies = $false
CleanupDownloadedExecutables = $false
CleanupDuplicateDownloads = $false
CleanupOutlookBackups = $false
CleanupITunesBackups = $false
CleanupAppleDownloads = $false
CleanupBrowserCache = $false
CleanupRevitJournals = $true
CleanupDeliveryOptimization = $false
CleanupComponentStore = $false
CleanupDiskCleanupItems = 'Standard'
}
}
function Get-SystemCleanupHandlers {
# Every VolumeCaches handler from Start-Cleanup.ps1, including disabled ones.
return @(
'Downloaded Program Files', 'Internet Cache Files', 'Offline Pages Files',
'Recycle Bin', 'Temporary Files', 'Thumbnail Cache', 'User file versions',
'Active Setup Temp Folders', 'BranchCache', 'Memory Dump Files',
'Old ChkDsk Files', 'RetailDemo Offline Content', 'System error memory dump files',
'System error minidump files', 'Temporary Setup Files', 'Windows Defender',
'Windows Error Reporting Archive Files', 'Windows Error Reporting Queue Files',
'Windows Error Reporting System Archive Files', 'Windows Error Reporting System Queue Files',
'Windows Error Reporting Temp Files', 'Service Pack Cleanup', 'Update Cleanup',
'Upgrade Discarded Files', 'Windows Upgrade Log Files', 'Previous Installations',
'Setup Log Files', 'Windows ESD installation files', 'Content Indexer Cleaner',
'Delivery Optimization Files', 'Device Driver Packages', 'GameNewsFiles',
'GameStatisticsFiles', 'GameUpdateFiles', 'Temporary Sync Files'
)
}
function Get-SystemCleanupDiskCleanupPresets {
$standard = @(
'Downloaded Program Files', 'Internet Cache Files', 'Thumbnail Cache',
'Active Setup Temp Folders', 'Temporary Setup Files', 'Windows Defender',
'RetailDemo Offline Content'
)
$updates = @('Service Pack Cleanup', 'Update Cleanup', 'Upgrade Discarded Files', 'Windows Upgrade Log Files')
$diagnostics = @(
'Memory Dump Files', 'Old ChkDsk Files', 'System error memory dump files',
'System error minidump files', 'Setup Log Files',
'Windows Error Reporting Archive Files', 'Windows Error Reporting Queue Files',
'Windows Error Reporting System Archive Files', 'Windows Error Reporting System Queue Files',
'Windows Error Reporting Temp Files'
)
return [ordered]@{
Standard = $standard
StandardAndUpdates = @($standard + $updates)
StandardUpdatesAndDiagnostics = @($standard + $updates + $diagnostics)
All = @(Get-SystemCleanupHandlers)
None = @()
}
}
function Resolve-SystemCleanupDiskCleanupItems {
param($Value)
$items = @($Value | ForEach-Object { ([string]$_).Split(',') } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
if (-not $items.Count) { throw 'CleanupDiskCleanupItems cannot be blank. Select None to disable Disk Cleanup.' }
$presets = Get-SystemCleanupDiskCleanupPresets
if ($items.Count -eq 1) {
foreach ($preset in $presets.Keys) {
if ($items[0] -ieq $preset) {
return [pscustomobject]@{ Preset = $preset; Items = @($presets[$preset]) }
}
}
}
# Exact lists remain supported for existing/manual callers. Presets cannot be
# combined with other presets or handlers; in particular, None must stand alone.
$handlers = @(Get-SystemCleanupHandlers)
$selected = @()
foreach ($item in $items) {
$match = @($handlers | Where-Object { $_ -ieq $item })
if (-not $match.Count) {
throw "Unknown Disk Cleanup preset or item: '$item'. Select one preset ($($presets.Keys -join ', ')) or exact handler names. Do not mix presets with other values."
}
if ($match[0] -notin $selected) { $selected += $match[0] }
}
return [pscustomobject]@{ Preset = 'Custom'; Items = @($selected) }
}
function Get-SystemCleanupOptions {
# Reject stale callers instead of silently re-enabling cleanup when their
# former false flag is ignored and the new Standard default takes effect.
if ($null -ne (Get-Variable -Name CleanupDiskCleanup -ErrorAction SilentlyContinue)) {
throw 'CleanupDiskCleanup has been removed. Remove it from Syncro/the caller and select CleanupDiskCleanupItems=None to disable Disk Cleanup.'
}
$options = @{}
$defaults = Get-SystemCleanupDefaults
foreach ($name in $defaults.Keys) {
$variable = Get-Variable -Name $name -ErrorAction SilentlyContinue
$value = if ($null -eq $variable) { $defaults[$name] } else { $variable.Value }
if ($defaults[$name] -is [bool]) {
# Do not cast RMM text to [bool]: [bool]'false' is true.
switch -Regex ([string]$value) {
'^(?i:\s*(\$?true|yes|1)\s*)$' { $value = $true; break }
'^(?i:\s*(\$?false|no|0)\s*)$' { $value = $false; break }
default { throw "$name must be true or false (received '$value')." }
}
} elseif ($defaults[$name] -is [int]) {
$number = 0
if (-not [int]::TryParse([string]$value, [ref]$number) -or $number -lt 1 -or $number -gt 3650) {
throw "$name must be a whole number from 1 to 3650."
}
$value = $number
} else {
$selection = Resolve-SystemCleanupDiskCleanupItems $value
$options.DiskCleanupPreset = $selection.Preset
$value = @($selection.Items)
}
$options[$name.Substring(7)] = $value
}
return $options
}
function Get-SystemCleanupOS {
$os = @(Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop)
if ($os.Count -ne 1 -or $os[0].ProductType -notin @(1, 2, 3)) {
throw 'Cannot identify OS ProductType; no cleanup will run.'
}
return [pscustomobject]@{ IsServer = ($os[0].ProductType -ne 1); Caption = $os[0].Caption }
}
function Write-SystemCleanupMessage {
param([string]$Message)
# Host/information stream keeps logs out of helper return values, even with Tools loaded.
Write-Host "[SystemCleanup] $Message"
}
function Test-SystemCleanupPath {
param([string]$Path, [string]$Root)
if ($Path -notmatch '^[A-Za-z]:\\' -or $Root -notmatch '^[A-Za-z]:\\') { return $false }
$full = [IO.Path]::GetFullPath($Path).TrimEnd('\')
$base = [IO.Path]::GetFullPath($Root).TrimEnd('\')
if ($base.Length -le 2 -or ($full -ne $base -and -not $full.StartsWith($base + '\', [StringComparison]::OrdinalIgnoreCase))) { return $false }
# Check every ancestor, not just the leaf. Never follow a junction into another tree.
$probe = $full
while ($probe.Length -gt 3) {
$item = Get-Item -LiteralPath $probe -Force -ErrorAction Stop
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { return $false }
$probe = Split-Path -Parent $probe
}
return $true
}
function Get-SystemCleanupChildren {
param([string]$Root)
if (-not (Test-Path -LiteralPath $Root)) { return }
if (-not (Test-SystemCleanupPath $Root $Root)) {
Write-SystemCleanupMessage "Skipping linked or unsafe path: $Root"
return
}
Get-ChildItem -LiteralPath $Root -Force -ErrorAction Stop | Where-Object { -not ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) }
}
function Get-SystemCleanupFiles {
param([string]$Root, [switch]$Recurse)
$pending = New-Object 'System.Collections.Generic.Stack[string]'
$pending.Push($Root)
while ($pending.Count) {
$directory = $pending.Pop()
foreach ($item in @(Get-SystemCleanupChildren $directory)) {
if ($item.PSIsContainer) { if ($Recurse) { $pending.Push($item.FullName) } }
else { $item }
}
}
}
function Remove-SystemCleanupFile {
param($Context, [string]$Category, [string]$Root, [string]$Path, [datetime]$Cutoff)
if (-not (Test-SystemCleanupPath $Path $Root)) { return }
$file = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
if ($file.PSIsContainer -or $file.LastWriteTimeUtc -ge $Cutoff) { return }
if ($Context.Options.ReportOnly) {
# Each category is an independent estimate. A disabled category must not
# consume a file before an enabled category can assess the same file.
$candidates = $Context.Candidates[$Category]
if ($candidates.ContainsKey($file.FullName)) { return }
$candidates[$file.FullName] = [long]$file.Length
} elseif (-not $Context.Seen.Add($file.FullName)) { return }
$stat = $Context.Stats[$Category]
$stat.CandidateBytes += $file.Length
$stat.CandidateFiles++
if ($Context.Options.ReportOnly) { return }
try {
# Literal leaf deletion only. In-use files are skipped, never force-unlocked.
Remove-Item -LiteralPath $file.FullName -Force -ErrorAction Stop
$stat.RemovedBytes += $file.Length
$stat.RemovedFiles++
} catch {
$stat.FailedFiles++
Write-SystemCleanupMessage "Skipped '$Path': $($_.Exception.Message)"
}
}
function Clear-SystemCleanupTree {
param($Context, [string]$Category, [string]$Root, [datetime]$Cutoff,
[string[]]$Include = @('*'), [string[]]$Exclude = @(), [switch]$Recurse)
foreach ($file in @(Get-SystemCleanupFiles $Root -Recurse:$Recurse)) {
$match = @($Include | Where-Object { $file.Name -like $_ }).Count -gt 0
if ($match -and @($Exclude | Where-Object { $file.Name -like $_ }).Count -eq 0) {
Remove-SystemCleanupFile $Context $Category $Root $file.FullName $Cutoff
}
}
# Ordinary temp/cache directories are retained. No recursive directory deletes.
}
function Invoke-SystemCleanupCategory {
param($Context, [string]$Name, [scriptblock]$Action)
$enabled = if ($Name -eq 'DiskCleanup') { @($Context.Options.DiskCleanupItems).Count -gt 0 } else { [bool]$Context.Options[$Name] }
if (-not $enabled -and -not $Context.Options.ReportOnly) { return }
$setting = "Cleanup$Name=$($enabled.ToString().ToLowerInvariant())"
$notes = ''
if ($Name -eq 'DiskCleanup') {
$selection = $Context.Options.DiskCleanupPreset
if ($selection -eq 'Custom') { $selection = $Context.Options.DiskCleanupItems -join ', ' }
$setting = "CleanupDiskCleanupItems=$selection"
$notes = if ($enabled) { "Selected handlers: $($Context.Options.DiskCleanupItems -join ', ')." } else { 'No handlers selected; Disk Cleanup will not run.' }
}
$blocked = $Context.OS.IsServer -and $Name -in @('ShadowCopies', 'DisableHibernation', 'CompactSearch',
'DownloadedExecutables', 'DuplicateDownloads', 'OutlookBackups', 'ITunesBackups', 'DiskCleanup')
$native = $Name -in @('DisableHibernation', 'CompactSearch', 'ShadowCopies', 'DeliveryOptimization', 'ComponentStore', 'DiskCleanup')
$Context.Stats[$Name] = [pscustomobject]@{
Category = $Name; Enabled = $enabled
CandidateFiles = $(if ($native -or $blocked) { $null } else { 0 })
CandidateBytes = $(if ($native -or $blocked) { $null } else { [long]0 })
RemovedFiles = 0; RemovedBytes = [long]0; FailedFiles = 0
Status = $(if ($Context.Options.ReportOnly) { 'Preview' } else { 'Completed' })
EstimateStatus = $(if ($native) { 'Not estimated' } else { 'Estimated' })
Setting = $setting; Notes = $notes
}
if ($blocked) {
$Context.Stats[$Name].Status = 'Blocked on server'
$Context.Stats[$Name].EstimateStatus = 'Not assessed'
Write-SystemCleanupMessage "BLOCKED on server OS: $Name ($setting)"
return
}
if ($Context.Options.ReportOnly) {
if (-not $Context.ContainsKey('Candidates')) { $Context.Candidates = @{} }
$Context.Candidates[$Name] = New-Object 'System.Collections.Generic.Dictionary[string,long]' ([StringComparer]::OrdinalIgnoreCase)
$selection = if ($enabled) { 'enabled for apply' } else { 'disabled; assessment only' }
Write-SystemCleanupMessage "Assessing $Name ($selection)."
}
try { & $Action } catch {
$Context.Stats[$Name].Status = 'Failed'
$Context.Stats[$Name].EstimateStatus = 'Incomplete'
$Context.Stats[$Name].Notes = $_.Exception.Message
$Context.Errors++
Write-SystemCleanupMessage "$Name failed: $($_.Exception.Message)"
}
if (-not $Context.Options.ReportOnly) {
$s = $Context.Stats[$Name]
if ($native) { Write-SystemCleanupMessage "$Name : $($s.Status); native savings not measured." }
else { Write-SystemCleanupMessage ("{0}: {1} eligible files / {2:N2} MiB; {3} removed / {4:N2} MiB; {5} skipped; {6}" -f $Name, $s.CandidateFiles, ($s.CandidateBytes / 1MB), $s.RemovedFiles, ($s.RemovedBytes / 1MB), $s.FailedFiles, $s.Status) }
}
}
function Set-SystemCleanupSkipped {
param($Context, [string]$Category, [string]$Reason, [string]$Status = 'Skipped')
$Context.Stats[$Category].Status = $Status
$Context.Stats[$Category].EstimateStatus = 'Not assessed'
$Context.Stats[$Category].Notes = $Reason
Write-SystemCleanupMessage $Reason
}
function Get-SystemCleanupReportTotals {
param($Context)
$enabled = New-Object 'System.Collections.Generic.Dictionary[string,long]' ([StringComparer]::OrdinalIgnoreCase)
$disabled = New-Object 'System.Collections.Generic.Dictionary[string,long]' ([StringComparer]::OrdinalIgnoreCase)
foreach ($row in $Context.Stats.Values) {
if ($row.Status -eq 'Blocked on server' -or -not $Context.Candidates.ContainsKey($row.Category)) { continue }
$target = if ($row.Enabled) { $enabled } else { $disabled }
foreach ($entry in $Context.Candidates[$row.Category].GetEnumerator()) { $target[$entry.Key] = $entry.Value }
}
$enabledBytes = [long]0; $additionalBytes = [long]0; $additionalFiles = 0
foreach ($size in $enabled.Values) { $enabledBytes += $size }
foreach ($entry in $disabled.GetEnumerator()) {
if (-not $enabled.ContainsKey($entry.Key)) { $additionalBytes += $entry.Value; $additionalFiles++ }
}
return [pscustomobject]@{
EnabledFiles = $enabled.Count; EnabledBytes = $enabledBytes
AdditionalDisabledFiles = $additionalFiles; AdditionalDisabledBytes = $additionalBytes
}
}
function Write-SystemCleanupReport {
param($Context)
Write-SystemCleanupMessage 'REPORT ONLY: no cleanup performed. Category estimates use the configured retention periods.'
foreach ($group in @('Enabled', 'Disabled', 'Blocked')) {
$rows = @($Context.Stats.Values | Where-Object {
if ($group -eq 'Blocked') { $_.Status -eq 'Blocked on server' }
else { $_.Status -ne 'Blocked on server' -and $_.Enabled -eq ($group -eq 'Enabled') }
} | Sort-Object Category)
$heading = switch ($group) {
Enabled { 'ENABLED - eligible for cleanup when CleanupReportOnly=false, subject to the listed conditions' }
Disabled { 'DISABLED - potential savings only; these categories will not run until enabled' }
Blocked { 'BLOCKED ON SERVER - not assessed and cannot be enabled on this OS' }
}
Write-SystemCleanupMessage $heading
if (-not $rows.Count) { Write-SystemCleanupMessage ' None.' }
foreach ($row in $rows) {
$estimate = switch ($row.EstimateStatus) {
'Not estimated' { 'space savings not estimated' }
'Not assessed' { 'space savings not assessed' }
default {
if ($null -eq $row.CandidateBytes) { 'space savings unavailable' }
else { '{0} eligible files / {1:N2} MiB' -f $row.CandidateFiles, ($row.CandidateBytes / 1MB) }
}
}
if ($row.EstimateStatus -eq 'Incomplete') { $estimate += ' (incomplete assessment)' }
Write-SystemCleanupMessage " $($row.Category) [$($row.Setting)]: $estimate; $($row.Status). $($row.Notes)"
}
}
$totals = Get-SystemCleanupReportTotals $Context
Write-SystemCleanupMessage ('Known unique file estimates in ENABLED categories: {0} files / {1:N2} MiB.' -f $totals.EnabledFiles, ($totals.EnabledBytes / 1MB))
Write-SystemCleanupMessage ('Additional unique file estimates in DISABLED categories, beyond enabled categories: {0} files / {1:N2} MiB.' -f $totals.AdditionalDisabledFiles, ($totals.AdditionalDisabledBytes / 1MB))
Write-SystemCleanupMessage 'Category estimates can overlap; the totals count each path once. Native savings and unassessed data are excluded; actual freed disk space may differ.'
}
function Test-SystemCleanupAppRunning {
param([string[]]$Names)
# Inventory failure aborts the category instead of assuming the app is closed.
return @((Get-Process -ErrorAction Stop) | Where-Object { $_.ProcessName -in $Names }).Count -gt 0
}
function Invoke-SystemCleanupProcess {
param($Context, [string]$FileName, [string]$Arguments)
$nativeDir = if ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess) { 'Sysnative' } else { 'System32' }
$executable = Join-Path $env:SystemRoot "$nativeDir\$FileName"
if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) { throw "Unavailable: $executable" }
Write-SystemCleanupMessage "$FileName $Arguments (native operation; size not estimated)"
if ($Context.Options.ReportOnly) { return }
$process = Start-Process -FilePath $executable -ArgumentList $Arguments -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop
if ($process.ExitCode -ne 0) { throw "$FileName returned exit code $($process.ExitCode)." }
}
function Remove-SystemCleanupDuplicates {
param($Context, [string]$Root, [datetime]$Cutoff)
$files = @(Get-SystemCleanupFiles $Root)
foreach ($duplicate in $files) {
if ($duplicate.LastWriteTimeUtc -ge $Cutoff -or $duplicate.BaseName -notmatch '^(.*) \([0-9]+\)$') { continue }
$originalName = $Matches[1] + $duplicate.Extension
$original = @($files | Where-Object { $_.Name -ieq $originalName -and $_.Length -eq $duplicate.Length })
if ($original.Count -ne 1) { continue }
if (-not (Test-SystemCleanupPath $duplicate.FullName $Root) -or -not (Test-SystemCleanupPath $original[0].FullName $Root)) { continue }
$originalStream = $null; $duplicateStream = $null
try {
# Hold read handles through deletion, refusing concurrent writers while hashing.
$sharing = [IO.FileShare]::Read -bor [IO.FileShare]::Delete
$originalStream = [IO.File]::Open($original[0].FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, $sharing)
$duplicateStream = [IO.File]::Open($duplicate.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, $sharing)
$hash = Get-FileHash -InputStream $duplicateStream -Algorithm SHA256 -ErrorAction Stop
$other = Get-FileHash -InputStream $originalStream -Algorithm SHA256 -ErrorAction Stop
if ($hash.Hash -eq $other.Hash) { Remove-SystemCleanupFile $Context 'DuplicateDownloads' $Root $duplicate.FullName $Cutoff }
} catch { Write-SystemCleanupMessage "Skipping changing/in-use duplicate '$($duplicate.FullName)': $($_.Exception.Message)" }
finally {
if ($duplicateStream) { $duplicateStream.Dispose() }
if ($originalStream) { $originalStream.Dispose() }
}
}
}
function Remove-SystemCleanupBundle {
param($Context, [string]$Category, [string]$Root, [datetime]$Cutoff)
# Backups and extracted installers are units: keep the entire unit if anything is recent,
# linked or inaccessible. Preflight in-use files before any deletion.
if (-not (Test-SystemCleanupPath $Root $Root)) { return }
$items = New-Object 'System.Collections.Generic.List[object]'
$pending = New-Object 'System.Collections.Generic.Stack[string]'
$pending.Push($Root)
while ($pending.Count) {
$dir = $pending.Pop()
foreach ($item in @(Get-ChildItem -LiteralPath $dir -Force -ErrorAction Stop)) {
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or $item.LastWriteTimeUtc -ge $Cutoff) { return }
$items.Add($item)
if ($item.PSIsContainer) { $pending.Push($item.FullName) }
}
}
if ((Get-Item -LiteralPath $Root -Force).LastWriteTimeUtc -ge $Cutoff) { return }
if (-not $Context.Options.ReportOnly) {
foreach ($file in @($items | Where-Object { -not $_.PSIsContainer })) {
try {
$probe = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
$probe.Dispose()
} catch { Write-SystemCleanupMessage "Retaining in-use bundle: $Root"; return }
}
}
foreach ($file in @($items | Where-Object { -not $_.PSIsContainer })) {
Remove-SystemCleanupFile $Context $Category $Root $file.FullName $Cutoff
}
if (-not $Context.Options.ReportOnly) {
foreach ($dir in @($items | Where-Object PSIsContainer | Sort-Object { $_.FullName.Length } -Descending) + @(Get-Item -LiteralPath $Root -Force)) {
if ((Test-SystemCleanupPath $dir.FullName $Root) -and @(Get-ChildItem -LiteralPath $dir.FullName -Force -ErrorAction Stop).Count -eq 0) {
# Directory.Delete without recursion cannot delete a newly populated directory.
[IO.Directory]::Delete($dir.FullName, $false)
}
}
}
}
function Get-SystemCleanupRecycleDate {
param([string]$MetadataPath)
if ((Get-Item -LiteralPath $MetadataPath -Force -ErrorAction Stop).Length -gt 1MB) { throw 'Oversized Recycle Bin metadata.' }
$bytes = [IO.File]::ReadAllBytes($MetadataPath)
if ($bytes.Length -lt 24) { throw 'Truncated Recycle Bin metadata.' }
$version = [BitConverter]::ToInt64($bytes, 0)
if ($version -notin @(1, 2)) { throw "Unknown Recycle Bin metadata version: $version" }
if ($version -eq 1 -and $bytes.Length -ne 544) { throw 'Invalid version 1 Recycle Bin metadata length.' }
if ($version -eq 2) {
if ($bytes.Length -lt 28) { throw 'Truncated version 2 Recycle Bin metadata.' }
$characters = [BitConverter]::ToUInt32($bytes, 24)
if ($characters -eq 0 -or (28L + 2L * $characters) -ne $bytes.Length) { throw 'Invalid version 2 Recycle Bin path length.' }
}
return [DateTime]::FromFileTimeUtc([BitConverter]::ToInt64($bytes, 16))
}
function Clear-SystemCleanupRecycleBin {
param($Context, [string]$Root, [datetime]$Cutoff)
foreach ($sid in @(Get-SystemCleanupChildren $Root | Where-Object { $_.PSIsContainer -and $_.Name -match '^S-1-' })) {
foreach ($metadata in @(Get-SystemCleanupFiles $sid.FullName | Where-Object { $_.Name -clike '$I*' })) {
try {
if ((Get-SystemCleanupRecycleDate $metadata.FullName) -ge $Cutoff) { continue }
$payload = Join-Path $sid.FullName ('$R' + $metadata.Name.Substring(2))
if (Test-Path -LiteralPath $payload) {
if (-not (Test-SystemCleanupPath $payload $sid.FullName)) { continue }
$item = Get-Item -LiteralPath $payload -Force -ErrorAction Stop
if ($item.PSIsContainer) {
Remove-SystemCleanupBundle $Context 'RecycleBin' $payload ([datetime]::MaxValue)
} else { Remove-SystemCleanupFile $Context 'RecycleBin' $sid.FullName $payload ([datetime]::MaxValue) }
}
# Keep metadata if the payload could not be fully removed.
if ($Context.Options.ReportOnly -or -not (Test-Path -LiteralPath $payload)) {
Remove-SystemCleanupFile $Context 'RecycleBin' $sid.FullName $metadata.FullName ([datetime]::MaxValue)
}
} catch { Write-SystemCleanupMessage "Skipping recycle item '$($metadata.FullName)': $($_.Exception.Message)" }
}
}
}
function Invoke-SystemCleanupDiskCleanup {
param($Context)
# Defence in depth: even direct helper calls cannot run cleanmgr on a server.
if ($Context.OS.IsServer) { throw 'Disk Cleanup is blocked on server OSes.' }
$selected = @($Context.Options.DiskCleanupItems)
Write-SystemCleanupMessage "Disk Cleanup selection: $($Context.Options.DiskCleanupPreset); selected items: $($selected -join ', '). Windows controls retention for these handlers."
if ($Context.Options.ReportOnly) {
$unselected = @((Get-SystemCleanupHandlers) | Where-Object { $_ -notin $selected })
Write-SystemCleanupMessage "Disk Cleanup items not selected (not run during apply): $($unselected -join ', '). Handler savings are not estimated."
return
}
if (-not $selected.Count) { return }
if (Test-SystemCleanupAppRunning @('cleanmgr')) { throw 'Another Disk Cleanup process is running.' }
$base = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches'
$keys = @(Get-ChildItem -LiteralPath $base -ErrorAction Stop)
# Pick an unused slot across ALL handlers, so a stale unrelated selection cannot run.
$used = @{}
foreach ($key in $keys) {
foreach ($valueName in $key.GetValueNames()) { $used[$valueName] = $true }
}
$slot = 0
foreach ($candidate in 1000..9999) {
if (-not $used.ContainsKey(('StateFlags{0:D4}' -f $candidate))) { $slot = $candidate; break }
}
if (-not $slot) { throw 'No unused Disk Cleanup settings slot is available.' }
$flag = 'StateFlags{0:D4}' -f $slot
$written = New-Object 'System.Collections.Generic.List[string]'
try {
foreach ($key in $keys) {
if ($key.PSChildName -in $selected) {
# Register before writing, so a partially successful write is restored too.
$written.Add($key.PSPath)
New-ItemProperty -LiteralPath $key.PSPath -Name $flag -Value 2 -PropertyType DWord -ErrorAction Stop | Out-Null
}
}
if ($written.Count) { Invoke-SystemCleanupProcess $Context 'cleanmgr.exe' "/sagerun:$slot" }
else { Write-SystemCleanupMessage 'None of the selected Disk Cleanup handlers are installed.' }
} finally {
# Wait for cleanmgr before removing ONLY the temporary settings owned by this run.
foreach ($path in $written) {
try { Remove-ItemProperty -LiteralPath $path -Name $flag -ErrorAction Stop }
catch { Write-SystemCleanupMessage "Could not remove temporary Disk Cleanup setting $path/$flag : $($_.Exception.Message)"; $Context.Errors++ }
}
}
}
function Invoke-SystemCleanupShadows {
param($Context)
if ($Context.OS.IsServer) { throw 'Shadow-copy deletion is blocked on server OSes.' }
$volumes = @(Get-CimInstance -ClassName Win32_Volume -ErrorAction Stop | Where-Object { $_.DriveLetter -eq $env:SystemDrive })
if ($volumes.Count -ne 1) { throw 'Could not uniquely identify the system volume.' }
$shadows = @(Get-CimInstance -ClassName Win32_ShadowCopy -ErrorAction Stop |
Where-Object { $_.VolumeName -eq $volumes[0].DeviceID } | Sort-Object InstallDate -Descending)
# Use exact IDs from the inventory; never loop /Oldest after a failed deletion.
foreach ($shadow in @($shadows | Select-Object -Skip 1)) {
if ($shadow.ID -notmatch '^\{[0-9a-fA-F-]{36}\}$') { throw 'Invalid shadow-copy identifier.' }
Invoke-SystemCleanupProcess $Context 'vssadmin.exe' "delete shadows /Shadow=$($shadow.ID) /Quiet"
}
}
function Invoke-SystemCleanupSearchCompaction {
param($Context)
if ($Context.OS.IsServer) { throw 'Search compaction is blocked on server OSes.' }
$database = Join-Path $env:ProgramData 'Microsoft\Search\Data\Applications\Windows\Windows.edb'
if (-not (Test-Path -LiteralPath $database -PathType Leaf)) { return }
if (-not (Test-SystemCleanupPath $database (Split-Path -Parent $database))) { return }
if ($Context.Options.ReportOnly) {
Write-SystemCleanupMessage "Would compact $database; size savings cannot be estimated."
return
}
$drive = New-Object IO.DriveInfo ([IO.Path]::GetPathRoot($database))
if ($drive.AvailableFreeSpace -lt ((Get-Item -LiteralPath $database).Length * 1.2)) { throw 'Insufficient free space for a temporary Search database (120% reserve required).' }
$service = Get-Service -Name WSearch -ErrorAction Stop
if ($service.Status -notin @('Running', 'Stopped')) { throw 'Windows Search is transitioning; try again later.' }
$wasRunning = $service.Status -eq 'Running'
try {
# Preserve the original startup configuration, including delayed automatic start.
if ($wasRunning) {
Stop-Service -Name WSearch -ErrorAction Stop
$service.WaitForStatus('Stopped', [timespan]::FromSeconds(30))
}
$temporary = Join-Path (Split-Path -Parent $database) ('SystemCleanup-' + [guid]::NewGuid().ToString('N') + '.edb')
Invoke-SystemCleanupProcess $Context 'esentutl.exe' ('/d "{0}" /t"{1}" /o' -f $database, $temporary)
} finally {
if ($wasRunning) { Start-Service -Name WSearch -ErrorAction Stop }
}
}
function Invoke-SystemCleanup {
param([hashtable]$Options)
$ErrorActionPreference = 'Stop'
$os = Get-SystemCleanupOS
if ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess) {
throw 'Run this script in 64-bit PowerShell to avoid filesystem and registry redirection.'
}
if (-not $Options.ReportOnly) {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal $identity
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Apply mode requires an elevated Administrator or SYSTEM token.' }
}
# One run per machine, including the registry slot allocation and native operations.
$mutex = New-Object Threading.Mutex($false, 'Global\Emberkom.Start-SystemCleanup')
$acquired = $false
try {
try { $acquired = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $acquired = $true }
if (-not $acquired) { throw 'Another Start-SystemCleanup run is already active.' }
$context = @{
Options = $Options; OS = $os; Stats = [ordered]@{}; Errors = 0; Candidates = @{}
Seen = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
}
Write-SystemCleanupMessage "OS: $($os.Caption); server: $($os.IsServer); report only: $($Options.ReportOnly)"
$now = [datetime]::UtcNow
$tempCutoff = $now.AddDays(-$Options.TempDays)
$diagnosticCutoff = $now.AddDays(-$Options.DiagnosticDays)
$backupCutoff = $now.AddDays(-$Options.BackupDays)
# Inventory registered profiles, including custom profile roots; no C:\Users wildcard.
$profiles = @(Get-CimInstance -ClassName Win32_UserProfile -ErrorAction Stop |
Where-Object { -not $_.Special -and $_.LocalPath } | Select-Object -ExpandProperty LocalPath -Unique)
$serviceProfiles = @(
(Join-Path $env:SystemRoot 'System32\config\systemprofile'),
(Join-Path $env:SystemRoot 'ServiceProfiles\LocalService'),
(Join-Path $env:SystemRoot 'ServiceProfiles\NetworkService')
)
if ([Environment]::Is64BitOperatingSystem) { $serviceProfiles += Join-Path $env:SystemRoot 'SysWOW64\config\systemprofile' }
$allProfiles = @($profiles + $serviceProfiles | Select-Object -Unique)
# Generic temp cleaning must not bypass the AutoCAD process check or dump retention.
$tempExclusions = @('*.ac$', '*.sv$', '*.dmp')
Invoke-SystemCleanupCategory $context 'SystemTemp' {
Clear-SystemCleanupTree $context 'SystemTemp' (Join-Path $env:SystemRoot 'Temp') $tempCutoff -Exclude $tempExclusions -Recurse
# Includes .evtx, computer-name logs, AppxErrorReport files, and Chocolatey temp.
}
Invoke-SystemCleanupCategory $context 'UserTemp' {
$acadRunning = Test-SystemCleanupAppRunning @('acad')
foreach ($profile in $profiles) {
$root = Join-Path $profile 'AppData\Local\Temp'
Clear-SystemCleanupTree $context 'UserTemp' $root $tempCutoff -Exclude $tempExclusions -Recurse
if (-not $acadRunning) { Clear-SystemCleanupTree $context 'UserTemp' $root $tempCutoff -Include @('*.ac$') -Recurse }
}
}
Invoke-SystemCleanupCategory $context 'ServiceTemp' {
foreach ($profile in $serviceProfiles) {
Clear-SystemCleanupTree $context 'ServiceTemp' (Join-Path $profile 'AppData\Local\Temp') $tempCutoff -Exclude $tempExclusions -Recurse
}
}
Invoke-SystemCleanupCategory $context 'ActiveCBSLog' {
$cbs = Join-Path $env:SystemRoot 'Logs\CBS'
$archives = @(Get-SystemCleanupFiles $cbs | Where-Object { $_.Name -like 'CbsPersist_*.log' -or $_.Name -like 'CbsPersist_*.cab' })
$total = ($archives | Measure-Object Length -Sum).Sum
# Do not stop Windows servicing to reclaim a log. Remove only when already idle.
if ($total -ge 200MB -and (Get-Service -Name TrustedInstaller -ErrorAction Stop).Status -eq 'Stopped') {
Clear-SystemCleanupTree $context 'ActiveCBSLog' $cbs $diagnosticCutoff -Include @('CBS.log')
} else { Write-SystemCleanupMessage 'Active CBS.log retained: servicing is active or archives total less than 200 MiB.' }
}
Invoke-SystemCleanupCategory $context 'CBSArchives' {
Clear-SystemCleanupTree $context 'CBSArchives' (Join-Path $env:SystemRoot 'Logs\CBS') $diagnosticCutoff -Include @('CbsPersist_*.log', 'CbsPersist_*.cab')
}
Invoke-SystemCleanupCategory $context 'CrashDumps' {
Clear-SystemCleanupTree $context 'CrashDumps' $env:SystemRoot $diagnosticCutoff -Include @('MEMORY.DMP')
foreach ($relative in @('Minidump', 'LiveKernelReports', 'Temp')) {
Clear-SystemCleanupTree $context 'CrashDumps' (Join-Path $env:SystemRoot $relative) $diagnosticCutoff -Include @('*.dmp') -Recurse
}
Clear-SystemCleanupTree $context 'CrashDumps' (Join-Path $env:ProgramData 'Genetec\Dumps') $diagnosticCutoff -Recurse
foreach ($profile in $allProfiles) {
foreach ($relative in @('AppData\Local\CrashDumps', 'AppData\Local\Temp')) {
Clear-SystemCleanupTree $context 'CrashDumps' (Join-Path $profile $relative) $diagnosticCutoff -Include @('*.dmp') -Recurse
}
}
}
Invoke-SystemCleanupCategory $context 'WERArchives' {
Clear-SystemCleanupTree $context 'WERArchives' (Join-Path $env:ProgramData 'Microsoft\Windows\WER\ReportArchive') $diagnosticCutoff -Recurse
foreach ($profile in $allProfiles) {
Clear-SystemCleanupTree $context 'WERArchives' (Join-Path $profile 'AppData\Local\Microsoft\Windows\WER\ReportArchive') $diagnosticCutoff -Recurse
}
}
Invoke-SystemCleanupCategory $context 'AutodeskInstallers' {
if (Test-SystemCleanupAppRunning @('setup', 'msiexec', 'AdskInstall', 'AdODIS')) { Set-SystemCleanupSkipped $context 'AutodeskInstallers' 'An installer is running; extracted Autodesk payloads retained.'; return }
foreach ($dir in @(Get-SystemCleanupChildren (Join-Path $env:SystemDrive 'Autodesk') | Where-Object { $_.PSIsContainer -and $_.Name -ne 'WI' })) {
Remove-SystemCleanupBundle $context 'AutodeskInstallers' $dir.FullName $tempCutoff
}
}
Invoke-SystemCleanupCategory $context 'RecycleBin' {
Clear-SystemCleanupRecycleBin $context (Join-Path $env:SystemDrive '$Recycle.Bin') $backupCutoff
}
Invoke-SystemCleanupCategory $context 'DownloadedExecutables' {
foreach ($profile in $profiles) { Clear-SystemCleanupTree $context 'DownloadedExecutables' (Join-Path $profile 'Downloads') $backupCutoff -Include @('*.exe') }
}
Invoke-SystemCleanupCategory $context 'DuplicateDownloads' {
foreach ($profile in $profiles) { Remove-SystemCleanupDuplicates $context (Join-Path $profile 'Downloads') $backupCutoff }
}
Invoke-SystemCleanupCategory $context 'OutlookBackups' {
if (Test-SystemCleanupAppRunning @('OUTLOOK')) { Set-SystemCleanupSkipped $context 'OutlookBackups' 'Outlook is running; backups retained.'; return }
foreach ($profile in $profiles) { Clear-SystemCleanupTree $context 'OutlookBackups' (Join-Path $profile 'AppData\Local\Microsoft\Outlook') $backupCutoff -Include @('*.bak') }
}
Invoke-SystemCleanupCategory $context 'ITunesBackups' {
if (Test-SystemCleanupAppRunning @('iTunes', 'AppleDevices')) { Set-SystemCleanupSkipped $context 'ITunesBackups' 'An Apple device application is running; backups retained.'; return }
foreach ($profile in $profiles) {
foreach ($relative in @('AppData\Roaming\Apple Computer\MobileSync\Backup', 'Apple\MobileSync\Backup')) {
foreach ($dir in @(Get-SystemCleanupChildren (Join-Path $profile $relative) | Where-Object PSIsContainer)) {
Remove-SystemCleanupBundle $context 'ITunesBackups' $dir.FullName $backupCutoff
}
}
}
}
Invoke-SystemCleanupCategory $context 'AppleDownloads' {
if (Test-SystemCleanupAppRunning @('iTunes', 'AppleDevices')) { Set-SystemCleanupSkipped $context 'AppleDownloads' 'An Apple device application is running; downloads retained.'; return }
foreach ($profile in $profiles) {
foreach ($device in @('iPhone', 'iPad', 'iPod')) {
Clear-SystemCleanupTree $context 'AppleDownloads' (Join-Path $profile "AppData\Roaming\Apple Computer\iTunes\$device Software Updates") $tempCutoff -Include @('*.ipsw')
}
Clear-SystemCleanupTree $context 'AppleDownloads' (Join-Path $profile 'Music\iTunes\iTunes Media\Mobile Applications') $tempCutoff -Include @('*.ipa')
}
}
Invoke-SystemCleanupCategory $context 'BrowserCache' {
foreach ($browser in @(@{Name='chrome'; Root='Google\Chrome\User Data'}, @{Name='msedge'; Root='Microsoft\Edge\User Data'})) {
if (Test-SystemCleanupAppRunning @($browser.Name)) {
$context.Stats.BrowserCache.Status = 'Partial'
$context.Stats.BrowserCache.EstimateStatus = 'Incomplete'
$context.Stats.BrowserCache.Notes += "$($browser.Name) is running; its cache was not assessed. "
Write-SystemCleanupMessage "$($browser.Name) is running; its caches retained."
continue
}
foreach ($profile in $profiles) {
foreach ($browserProfile in @(Get-SystemCleanupChildren (Join-Path $profile ('AppData\Local\' + $browser.Root)) | Where-Object { $_.PSIsContainer -and ($_.Name -eq 'Default' -or $_.Name -match '^Profile \d+$') })) {
foreach ($cache in @('Cache', 'Code Cache', 'GPUCache')) {
Clear-SystemCleanupTree $context 'BrowserCache' (Join-Path $browserProfile.FullName $cache) $tempCutoff -Recurse
}
}
}
}
}
Invoke-SystemCleanupCategory $context 'RevitJournals' {
if (Test-SystemCleanupAppRunning @('Revit')) { Set-SystemCleanupSkipped $context 'RevitJournals' 'Revit is running; journals retained.'; return }
foreach ($profile in $profiles) {
foreach ($version in @(Get-SystemCleanupChildren (Join-Path $profile 'AppData\Local\Autodesk\Revit') | Where-Object { $_.PSIsContainer -and $_.Name -like 'Autodesk Revit *' })) {
Clear-SystemCleanupTree $context 'RevitJournals' (Join-Path $version.FullName 'Journals') $diagnosticCutoff -Include @('journal*.txt')
}
}
}
Invoke-SystemCleanupCategory $context 'DisableHibernation' {
if (Test-Path -LiteralPath (Join-Path $env:SystemDrive 'hiberfil.sys')) { Invoke-SystemCleanupProcess $context 'powercfg.exe' '/hibernate off' }
}
Invoke-SystemCleanupCategory $context 'CompactSearch' { Invoke-SystemCleanupSearchCompaction $context }
Invoke-SystemCleanupCategory $context 'ShadowCopies' { Invoke-SystemCleanupShadows $context }
Invoke-SystemCleanupCategory $context 'DeliveryOptimization' {
if (-not (Get-Command Delete-DeliveryOptimizationCache -ErrorAction SilentlyContinue)) {
if ($Options.ReportOnly) { Set-SystemCleanupSkipped $context 'DeliveryOptimization' 'Delivery Optimization cmdlet is not installed.' -Status 'Unavailable'; return }
throw 'Delivery Optimization cmdlet is not installed.'
}
Write-SystemCleanupMessage 'Delivery Optimization: unpinned cache only; size not estimated.'
if (-not $Options.ReportOnly) { Delete-DeliveryOptimizationCache -Force -ErrorAction Stop }
}
Invoke-SystemCleanupCategory $context 'ComponentStore' {
Invoke-SystemCleanupProcess $context 'schtasks.exe' '/Run /TN "\Microsoft\Windows\Servicing\StartComponentCleanup"'
Write-SystemCleanupMessage 'Component cleanup runs asynchronously under Task Scheduler; completion and reclaimed bytes are not measured here.'
}
Invoke-SystemCleanupCategory $context 'DiskCleanup' { Invoke-SystemCleanupDiskCleanup $context }
if ($Options.ReportOnly) { Write-SystemCleanupReport $context }
if ($context.Errors) { throw "$($context.Errors) cleanup category/maintenance error(s). Review the category messages above." }
return @($context.Stats.Values | Sort-Object @{Expression={ if ($_.Status -eq 'Blocked on server') { 2 } elseif ($_.Enabled) { 0 } else { 1 } }}, Category)
} finally {
if ($acquired) { $mutex.ReleaseMutex() }
$mutex.Dispose()
}
}
# Read inherited caller variables before entering the implementation's local scope.
Invoke-SystemCleanup -Options (Get-SystemCleanupOptions)