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)
+220
View File
@@ -0,0 +1,220 @@
# System cleanup
`Start-SystemCleanup.ps1` combines the operations of `Cleanup-SystemTempFiles.ps1`
and `Start-Cleanup.ps1`, with additional cache and diagnostic targets. The old
scripts remain unchanged. Upload `rmm/Start-SystemCleanup.ps1` to the RMM and run
as SYSTEM under **64-bit Windows PowerShell 5.1**. No reboot is initiated.
On 64-bit Windows the core rejects a 32-bit host before changes.
## First run and configuration
Define the script variables in Syncro using the names below **without `$`**.
Use Dropdown variables with `true` and `false` choices for boolean options, and
a single-selection Dropdown for `CleanupDiskCleanupItems` with the five presets
below. Select `Standard` for the usual Disk Cleanup behavior. The three day counts
can be Runtime variables, requiring a nonempty number each run; omit those variable
definitions if you want the core's defaults instead. Syncro supplies all values as
strings. Uploading the shim does not create these variable definitions in Syncro.
Remove the former `CleanupDiskCleanup` variable from Syncro and any manual callers.
`CleanupDiskCleanupItems=None` is now the only operator setting to disable native
Disk Cleanup. A caller still supplying the removed boolean fails before cleanup,
with migration instructions, so an old `false` value cannot be silently ignored.
Like `rmm/Install-MicrosoftOffice365.ps1`, the shim documents the variables but
does not assign them. It loads Tools.ps1 and calls
`Run-Script -LivePSScript Start-SystemCleanup`, preserving Syncro's injected
variables through the dot-sourced caller scope; do not add `-Arguments`. The core
parses these strings and supplies defaults for absent variables, including direct
use. The core does not need to download Tools.ps1 itself.
Run once with `CleanupReportOnly=true`, then set it to `false` to apply. Report
mode assesses **all categories regardless of their enablement**, using the current
retention settings. It leaves the enablement variables unchanged. The final report
has three sections:
- **Enabled:** eligible for cleanup on an apply run, subject to the reported conditions.
- **Disabled:** potential savings only; these categories will not run during apply
unless you enable their corresponding `Cleanup*` variables.
- **Blocked on server:** listed for visibility, without scanning or executing their
actions. These cannot be enabled on a server.
For example, `CleanupDownloadedExecutables=false` still reports old downloaded
executables in the Disabled section on a client. With `CleanupReportOnly=false`,
that category is skipped entirely until explicitly enabled.
File categories report their independent eligible file counts and logical bytes.
These category estimates can overlap (for example, a duplicate downloaded EXE).
The enabled total counts each file path once. The disabled total shows additional
unique file bytes beyond those already counted in enabled categories. Native
operations such as Disk Cleanup, VSS, Search compaction, Delivery Optimization,
component cleanup, and disabling hibernation say **not estimated**, not zero.
Disk Cleanup also lists its preset (or custom list), expanded selected handlers,
and unselected handlers without running them. `None` places Disk Cleanup in the
Disabled section; the report still lists the unselected handlers. Servers always
place it in the Blocked section, regardless of the preset.
Skipped/unavailable categories say **not assessed**; failed or partially assessed
categories are labeled incomplete. In-use application checks remain enforced, so
close those applications and rerun to obtain their estimates. Unknown savings are
excluded from the totals, and file sizes do not guarantee physical space savings.
Report mode does not delete files, change registry settings, stop services,
launch maintenance programs, or request scheduled maintenance. Acquiring a named
mutex prevents overlapping runs; the RMM bootstrap still downloads Tools/core
and may produce its usual logs. Native cleanup savings cannot be estimated.
Boolean options accept native booleans or true/false, yes/no, 1/0 strings. Blank
or unrecognized boolean values fail before cleanup. Retention values must be
whole days from 1 through 3650. Unknown Disk Cleanup presets/handler names, blank
selections, and mixtures of presets with other values also fail before cleanup.
| Variable | Default | Purpose |
| --- | --- | --- |
| `CleanupReportOnly` | true | Assess all categories versus apply enabled categories only |
| `CleanupTempDays` | 7 | Temp files, installers, browser cache, Apple downloads |
| `CleanupDiagnosticDays` | 30 | CBS, WER archives, dumps, Revit journals |
| `CleanupBackupDays` | 30 | Downloads, backups, time spent in Recycle Bin |
| `CleanupSystemTemp` | true | Windows Temp, including EVTX, misc logs, AppxErrorReport, Chocolatey |
| `CleanupUserTemp` | true | Registered user profiles' Local Temp; AutoCAD `.ac$` only with AutoCAD closed |
| `CleanupServiceTemp` | true | LocalService, NetworkService, SYSTEM profile temp folders |
| `CleanupCBSArchives` | true | `CbsPersist_*.log` and `CbsPersist_*.cab` |
| `CleanupActiveCBSLog` | false | Old CBS.log, only with TrustedInstaller already stopped and archives >=200 MiB |
| `CleanupCrashDumps` | true | MEMORY.DMP, Minidump, LiveKernelReports including PDCRevocation, Genetec Dumps, user/service CrashDumps and temp `.dmp` |
| `CleanupWERArchives` | true | System/user/service WER ReportArchive; queues retained |
| `CleanupAutodeskInstallers` | false | Old extracted directories under system drive Autodesk, excluding WI |
| `CleanupRecycleBin` | false | System-drive recycle items, using deletion date from `$I` metadata |
| `CleanupDisableHibernation` | false | `powercfg /hibernate off` |
| `CleanupCompactSearch` | false | Compact Windows.edb with esentutl; temporarily stop WSearch |
| `CleanupShadowCopies` | false | Delete all but newest system-volume shadow copy |
| `CleanupDownloadedExecutables` | false | Old `.exe` files in each profile's Downloads |
| `CleanupDuplicateDownloads` | false | Old `name (number).ext` files with a matching original and SHA-256 |
| `CleanupOutlookBackups` | false | Old Outlook `.bak` files, with Outlook closed |
| `CleanupITunesBackups` | false | Old complete MobileSync backup directories, with Apple apps closed |
| `CleanupAppleDownloads` | false | Old IPSW/IPA files from the previously commented-out iTunes block |
| `CleanupBrowserCache` | false | Chrome/Edge Cache, Code Cache, GPUCache in Default/Profile N, with that browser closed |
| `CleanupRevitJournals` | true | Old journal*.txt only, with Revit closed |
| `CleanupDeliveryOptimization` | false | Supported cache cmdlet, retaining pinned content |
| `CleanupComponentStore` | false | Request Windows StartComponentCleanup scheduled task; asynchronous |
| `CleanupDiskCleanupItems` | Standard | Disk Cleanup preset; None disables it; clients only. Exact handler lists/arrays also accepted |
## Disk Cleanup presets
Configure these exact dropdown choices for `CleanupDiskCleanupItems`:
| Preset | Selected handlers |
| --- | --- |
| `Standard` (default) | Downloaded Program Files; Internet Cache Files; Thumbnail Cache; Active Setup Temp Folders; Temporary Setup Files; Windows Defender; RetailDemo Offline Content |
| `StandardAndUpdates` | All Standard handlers, plus Service Pack Cleanup; Update Cleanup; Upgrade Discarded Files; Windows Upgrade Log Files |
| `StandardUpdatesAndDiagnostics` | All StandardAndUpdates handlers, plus 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 |
| `All` | All 35 supported legacy handlers listed below, including Recycle Bin, user file versions, previous installations, and Windows ESD installation files |
| `None` | No handlers; native Disk Cleanup does not run |
Presets are cumulative and case-insensitive; surrounding whitespace is ignored.
`Standard` preserves the previous default selection. `All` selects the explicit
supported list, not arbitrary additional handlers installed on an endpoint.
No preset changes other `Cleanup*` flags or bypasses the server exclusion.
Exact comma-separated handler names and arrays remain supported for manual or
existing callers, for example `Thumbnail Cache,Internet Cache Files`. They are
reported as a custom selection. Use one preset or a list of exact handlers; do
not mix them. A supplied blank/null value is invalid; an absent variable defaults
to `Standard`. Use the nonempty value `None` to disable native Disk Cleanup.
## Server policy
`Win32_OperatingSystem.ProductType` identifies clients (1), domain controllers
(2), and other servers (3). Both server types are blocked from these categories,
even if enabled or selected by a Disk Cleanup preset:
- ShadowCopies
- DisableHibernation
- CompactSearch
- DownloadedExecutables and DuplicateDownloads
- OutlookBackups and ITunesBackups
- DiskCleanup (every handler, including any newly selected items)
Unknown or failed OS identification stops the run before changes. There is no
override. Disk Cleanup availability varies by Server version/installation; the
OS gate is enforced even if cleanmgr.exe exists. Native and file categories
outside this list can run on both clients and servers when enabled.
## All legacy Disk Cleanup operations
Every handler from Start-Cleanup.ps1 remains selectable, including those that
were disabled there. The old groups are listed here for migration; select a
preset above or exact handler names in `CleanupDiskCleanupItems`. The old group
names themselves are not accepted as presets.
| Old group | Handler names |
| --- | --- |
| User | Downloaded Program Files; Internet Cache Files; Offline Pages Files; Recycle Bin; Temporary Files; Thumbnail Cache; User file versions |
| System | Active Setup Temp Folders; BranchCache; Memory Dump Files; Old ChkDsk Files; RetailDemo Offline Content; Temporary Files; 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 |
| WindowsUpdate | Service Pack Cleanup; Update Cleanup; Upgrade Discarded Files; Windows Upgrade Log Files |
| WindowsPreviousVersions | Previous Installations; Setup Log Files |
| Invasive | Windows ESD installation files |
| Misc | Content Indexer Cleaner; Delivery Optimization Files; Device Driver Packages; GameNewsFiles; GameStatisticsFiles; GameUpdateFiles; Temporary Sync Files |
Selecting a handler explicitly permits Windows to apply that handler's own
retention rules. The script's day settings **do not apply to cleanmgr**. For
example, its Recycle Bin/dump/WER handlers can remove recent data; its previous
installation/service pack/ESD handlers can remove rollback or recovery options.
`/sagerun` enumerates drives; it is not restricted to the system drive. The
default selection omits those recovery and diagnostic handlers.
Instead of persistent sageset flags or legacy NoSettings/NoCleaning/DeleteSettings
modes, each live run allocates an unused settings slot across all registered
handlers, writes only selected handlers, waits for cleanmgr, then removes its own
temporary flags in finally. Existing settings are preserved. Abnormal process
termination can leave a temporary slot behind; future runs skip occupied slots.
## Deletion and operational boundaries
- Inspect each file's modification time; an old parent never authorizes deletion
of newer children. Ordinary cache/temp directories are retained.
- Use literal local paths, verify containment, and skip reparse points and linked
ancestors (including OneDrive placeholders). UNC paths and redirected profile
folders reached through links are skipped. No ownership or ACL changes.
- Skip in-use files. A category inventory failure is reported and later categories
continue; the run fails at the end if a category/maintenance operation failed.
- Generic temp cleanup excludes `.dmp`, `.ac$`, and AutoCAD `.sv$` autosaves.
Dumps get diagnostic retention; `.ac$` gets a separate closed-app check;
`.sv$` is retained. Revit model/recovery files and browser site storage are
outside the dedicated cache/journal targets.
- Backup/installer directories are inspected as complete units. Recent content
or links retain the unit, and apply mode probes for in-use files before deleting
any part of a unit. No recursive Remove-Item is used. Failed file deletion
retains the remaining directory; there is no transaction or rollback.
- Recycle Bin cleanup uses `$I` FILETIME metadata and removes the paired `$R`
content before its metadata. Unsupported/corrupt metadata is retained.
- Downloads are not discovered via redirected Known Folders. Duplicate matching
requires extension, size, and SHA-256 equality. Read handles prevent concurrent
writes during hashing/deletion; filesystem activity outside the script can still
rename or delete files, so this remains an opt-in operation.
- Active CBS cleanup never stops TrustedInstaller. Search compaction preserves
service startup settings, requires free space for a temporary database, and
restarts WSearch in finally only if it was originally running. An interrupted
native compaction can leave its uniquely named temporary database for inspection.
- VSS deletion uses exact inventoried snapshot IDs and preserves the newest;
native failures stop that category. Backup-managed snapshots may refuse deletion.
- Component cleanup uses Windows' scheduled task, with no ResetBase or direct
WinSxS deletion. Task submission is reported separately from completion.
- Native operations report exit codes and use hidden windows. No hard execution
timeout is imposed; allow adequate RMM runtime if enabling maintenance work.
- Byte counters are file lengths, not guaranteed physical disk savings (compression,
sparse files, hard links, and native cleanup affect actual reclaimed space).
## Validation
Run `powershell.exe -NoProfile -File tests/Start-SystemCleanup.Tests.ps1`.
Tests load function definitions via the AST, use disposable fixture directories,
and mock OS, registry, native processes, and service operations. They do not run
cleanup against the host's Windows folders or invoke maintenance programs.
Coverage includes disabled-category estimates, separate report groups, unique
totals for overlapping categories, and disabled categories remaining untouched in
apply mode. Preset tests verify exact handler membership, cumulative selections,
RMM scope preservation, None disabling native work, and the server exclusions.
References: [OS ProductType](https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-operatingsystem),
[Disk Cleanup](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cleanmgr),
[component cleanup](https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/clean-up-the-winsxs-folder),
[Windows Search](https://learn.microsoft.com/troubleshoot/windows-client/shell-experience/windows-search-performance-issues).
+49
View File
@@ -0,0 +1,49 @@
#Requires -Version 5.1
# Configure these [string] Dropdown variables in Syncro, each with true/false choices:
# [string]$CleanupReportOnly - true (default: assess all), false (apply enabled only)
# [string]$CleanupSystemTemp - true (default), false
# [string]$CleanupUserTemp - true (default), false
# [string]$CleanupServiceTemp - true (default), false
# [string]$CleanupCBSArchives - true (default), false
# [string]$CleanupActiveCBSLog - false (default), true
# [string]$CleanupCrashDumps - true (default), false
# [string]$CleanupWERArchives - true (default), false
# [string]$CleanupAutodeskInstallers - false (default), true
# [string]$CleanupRecycleBin - false (default), true
# [string]$CleanupDisableHibernation - false (default), true
# [string]$CleanupCompactSearch - false (default), true
# [string]$CleanupShadowCopies - false (default), true
# [string]$CleanupDownloadedExecutables - false (default), true
# [string]$CleanupDuplicateDownloads - false (default), true
# [string]$CleanupOutlookBackups - false (default), true
# [string]$CleanupITunesBackups - false (default), true
# [string]$CleanupAppleDownloads - false (default), true
# [string]$CleanupBrowserCache - false (default), true
# [string]$CleanupRevitJournals - true (default), false
# [string]$CleanupDeliveryOptimization - false (default), true
# [string]$CleanupComponentStore - false (default), true
# Configure this [string] Dropdown variable in Syncro with these exact choices:
# [string]$CleanupDiskCleanupItems - Standard (default)
# StandardAndUpdates
# StandardUpdatesAndDiagnostics
# All
# None
# None disables native Disk Cleanup. All includes Recycle Bin and recovery data.
# Configure these [string] Runtime variables if you need custom retention values:
# [string]$CleanupTempDays - 7 (default); whole days, 1-3650
# [string]$CleanupDiagnosticDays - 30 (default); whole days, 1-3650
# [string]$CleanupBackupDays - 30 (default); whole days, 1-3650
# Runtime values must be entered each run; omit these variables to use core defaults.
# Uploading this file does not define the variables or their selections in Syncro.
# Syncro injects the variables into the caller scope. Do not assign over them here.
# The main script parses the injected strings and supplies defaults for absent variables.
# Every variable configured in Syncro needs a nonempty value.
# Report-only assesses enabled AND disabled categories in separate report sections.
# Server-blocked categories are listed without assessment. Native savings may be unknown.
# Server exclusions cannot be overridden by these variables. No reboot is initiated.
$ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
. $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1')))
# No -Arguments: Run-Script must dot-source the core into this caller's scope.
Run-Script -LivePSScript Start-SystemCleanup
+487
View File
@@ -0,0 +1,487 @@
#Requires -Version 5.1
# Offline: AST-load cleanup functions; mock shim downloads and native operations.
$ErrorActionPreference = 'Stop'
$repo = Split-Path -Parent $PSScriptRoot
$testRoot = Join-Path $env:TEMP ('SystemCleanupTests-' + [guid]::NewGuid().ToString('N'))
$null = New-Item -ItemType Directory -Path $testRoot
$script:assertions = 0
function Assert-Cleanup { param([bool]$Condition, [string]$Message) $script:assertions++; if (-not $Condition) { throw $Message } }
function Assert-CleanupThrows {
param([scriptblock]$Action, [string]$Pattern)
$caught = $null
try { & $Action | Out-Null } catch { $caught = $_ }
Assert-Cleanup ($null -ne $caught -and $caught.Exception.Message -match $Pattern) "Expected '$Pattern', got '$caught'."
}
function Read-CleanupAst {
param([string]$File)
$tokens = $null; $errors = $null
$ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $repo $File), [ref]$tokens, [ref]$errors)
if ($errors.Count) { throw ($errors | Out-String) }
return $ast
}
function New-CleanupFixture {
param([string]$Relative, [string]$Content = 'fixture', [int]$Days = 60)
$path = Join-Path $testRoot $Relative
$null = [IO.Directory]::CreateDirectory((Split-Path -Parent $path))
[IO.File]::WriteAllText($path, $Content)
[IO.File]::SetLastWriteTimeUtc($path, [datetime]::UtcNow.AddDays(-$Days))
return $path
}
try {
$core = Read-CleanupAst 'Start-SystemCleanup.ps1'
$shim = Read-CleanupAst 'rmm/Start-SystemCleanup.ps1'
foreach ($definition in $core.FindAll({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst]}, $false)) {
. ([scriptblock]::Create($definition.Extent.Text))
}
$script:messages = @()
function Write-SystemCleanupMessage { param($Message) $script:messages += $Message }
function New-CleanupContext {
param([bool]$ReportOnly = $true, [bool]$Server = $false)
return @{
Options = Get-SystemCleanupOptions; OS = [pscustomobject]@{IsServer=$Server; Caption='Fixture'}
Stats=[ordered]@{}; Errors=0
Seen=New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
} | ForEach-Object { $_.Options.ReportOnly=$ReportOnly; $_ }
}
# Defaults and RMM shared scope: values defined outside the loader must survive.
$options = Get-SystemCleanupOptions
Assert-Cleanup ($options.ReportOnly -and $options.TempDays -eq 7 -and $options.DiagnosticDays -eq 30) 'Unsafe defaults.'
Assert-Cleanup ($options.DiskCleanupPreset -eq 'Standard' -and -not $options.ContainsKey('DiskCleanup')) 'Disk Cleanup must use a single selection, defaulting to Standard.'
# Lock down the intended policy: adding handlers changes what operators permit.
$expectedStandard = @('Downloaded Program Files','Internet Cache Files','Thumbnail Cache','Active Setup Temp Folders','Temporary Setup Files','Windows Defender','RetailDemo Offline Content')
$expectedUpdates = @('Service Pack Cleanup','Update Cleanup','Upgrade Discarded Files','Windows Upgrade Log Files')
$expectedDiagnostics = @('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')
$expectedPresets = [ordered]@{
Standard = $expectedStandard
StandardAndUpdates = @($expectedStandard + $expectedUpdates)
StandardUpdatesAndDiagnostics = @($expectedStandard + $expectedUpdates + $expectedDiagnostics)
All = @(Get-SystemCleanupHandlers)
None = @()
}
foreach ($presetName in $expectedPresets.Keys) {
& {
$CleanupDiskCleanupItems = ' ' + $presetName.ToLowerInvariant() + ' '
$parsed = Get-SystemCleanupOptions
Assert-Cleanup ($parsed.DiskCleanupPreset -ceq $presetName) "Preset normalization failed: $presetName"
Assert-Cleanup (($parsed.DiskCleanupItems -join '|') -ceq ($expectedPresets[$presetName] -join '|')) "Unexpected cleanup scope for $presetName"
Assert-Cleanup ($parsed.DiskCleanupItems -is [array]) "Preset $presetName did not produce an array."
}
}
& {
$CleanupDiskCleanupItems = @(' thumbnail cache ', 'INTERNET CACHE FILES', 'Thumbnail Cache')
$parsed = Get-SystemCleanupOptions
Assert-Cleanup ($parsed.DiskCleanupPreset -eq 'Custom' -and ($parsed.DiskCleanupItems -join ',') -ceq 'Thumbnail Cache,Internet Cache Files') 'Custom arrays must normalize and deduplicate handlers.'
foreach ($invalid in @('Standrad', 'None,Thumbnail Cache', 'Standard,All', 'Standard,Internet Cache Files')) {
$CleanupDiskCleanupItems = $invalid
Assert-CleanupThrows { Get-SystemCleanupOptions } 'Unknown Disk Cleanup preset or item'
}
foreach ($blank in @('', ' ', ',', $null, @())) {
$CleanupDiskCleanupItems = $blank
Assert-CleanupThrows { Get-SystemCleanupOptions } 'cannot be blank'
}
}
& {
foreach ($oldValue in @('false', 'true')) {
$CleanupDiskCleanup = $oldValue
Assert-CleanupThrows { Get-SystemCleanupOptions } 'CleanupDiskCleanup has been removed'
}
}
& {
$CleanupReportOnly = 'false'; $CleanupShadowCopies = ' no '; $CleanupTempDays = '14'
$CleanupDiskCleanupItems = 'Thumbnail Cache,Internet Cache Files'
$o = Get-SystemCleanupOptions
Assert-Cleanup (-not $o.ReportOnly -and -not $o.ShadowCopies -and $o.TempDays -eq 14 -and $o.DiskCleanupItems.Count -eq 2) 'Caller scope/text parsing failed.'
Assert-Cleanup ($CleanupReportOnly -ceq 'false' -and $CleanupTempDays -ceq '14') 'Caller variables were overwritten.'
$CleanupReportOnly = 'maybe'; Assert-CleanupThrows { Get-SystemCleanupOptions } 'must be true or false'
$CleanupReportOnly = $true; $CleanupTempDays = 0; Assert-CleanupThrows { Get-SystemCleanupOptions } 'whole number'
$CleanupTempDays = 7; $CleanupDiskCleanupItems = 'Unknown handler'; Assert-CleanupThrows { Get-SystemCleanupOptions } 'Unknown Disk Cleanup'
}
$legacy = Get-Content -LiteralPath (Join-Path $repo 'Start-Cleanup.ps1') -Raw
$legacyHandlers = @([regex]::Matches($legacy, '"([^"\r\n]+)"\s*=\s*\$(?:true|false);') | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique)
foreach ($handler in $legacyHandlers) { Assert-Cleanup ($handler -in (Get-SystemCleanupHandlers)) "Lost legacy cleanup handler: $handler" }
Assert-Cleanup ($legacyHandlers.Count -eq (Get-SystemCleanupHandlers).Count) 'Unexpected handler inventory mismatch.'
$runCommand = $shim.Find({param($n) $n -is [Management.Automation.Language.CommandAst] -and $n.GetCommandName() -eq 'Run-Script'}, $true)
Assert-Cleanup ($runCommand.Extent.Text -eq 'Run-Script -LivePSScript Start-SystemCleanup') 'Shim must use dot-sourcing Run-Script without Arguments.'
& {
# Exercise the actual shim and real Run-Script with Syncro-style strings.
# Both download implementations return inert source; no real WebClient is created.
$toolsAst=Read-CleanupAst 'Tools.ps1'
$runner=$toolsAst.Find({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq 'Run-Script'}, $true)
$script:cleanupMockTools=$runner.Extent.Text
$fixtureWorkload=New-CleanupFixture 'rmm-scope.ps1' 'Get-SystemCleanupOptions'
function IsURLValid { return $true }
function Download-File { return $fixtureWorkload }
function New-Object {
param($TypeName)
if ($TypeName -ne 'Net.WebClient') { throw "Unexpected object in shim probe: $TypeName" }
$client=[pscustomobject]@{}
$client | Add-Member ScriptMethod DownloadString {
param($URL)
if ($URL -match '/Tools\.ps1$') { return $script:cleanupMockTools }
if ($URL -match '/Start-SystemCleanup\.ps1$') { return 'Get-SystemCleanupOptions' }
throw "Unexpected URL in shim probe: $URL"
}
return $client
}
[string]$CleanupReportOnly='false'
[string]$CleanupSystemTemp='false'
[string]$CleanupTempDays='14'
foreach ($selectionName in @($expectedPresets.Keys) + @('Thumbnail Cache')) {
[string]$CleanupDiskCleanupItems=$selectionName
$output=@(. ([scriptblock]::Create($shim.Extent.Text)))
$selected=@($output | Where-Object { $_ -is [hashtable] })
Assert-Cleanup ($selected.Count -eq 1) 'Shim did not return the inert workload result.'
$injectedOptions=$selected[0]
Assert-Cleanup (-not $injectedOptions.ReportOnly -and -not $injectedOptions.SystemTemp -and $injectedOptions.TempDays -eq 14) 'Run-Script lost Syncro-injected strings.'
$expectedItems = if ($selectionName -eq 'Thumbnail Cache') { @('Thumbnail Cache') } else { @($expectedPresets[$selectionName]) }
Assert-Cleanup (($injectedOptions.DiskCleanupItems -join '|') -ceq ($expectedItems -join '|')) "Run-Script lost the injected selection: $selectionName"
Assert-Cleanup ($injectedOptions.DiagnosticDays -eq 30 -and $CleanupReportOnly -ceq 'false' -and $CleanupTempDays -ceq '14' -and $CleanupDiskCleanupItems -ceq $selectionName) 'Absent defaults or original caller variables changed.'
}
}
# All server/DC gates, including when enabled, and unknown OS failure.
$blocked = @('ShadowCopies','DisableHibernation','CompactSearch','DownloadedExecutables','DuplicateDownloads','OutlookBackups','ITunesBackups','DiskCleanup')
& {
function Get-CimInstance { param($ClassName) if ($ClassName -eq 'Win32_OperatingSystem') { [pscustomobject]@{ProductType=$script:productType; Caption='Fixture OS'} } }
foreach ($script:productType in @(1,2,3)) {
$os = Get-SystemCleanupOS
Assert-Cleanup ($os.IsServer -eq ($script:productType -ne 1)) 'ProductType classification failed.'
$c = New-CleanupContext -Server $os.IsServer
foreach ($name in $blocked) {
if ($name -ne 'DiskCleanup') { $c.Options[$name]=$true }
$script:ran=$false
Invoke-SystemCleanupCategory $c $name { $script:ran=$true }
Assert-Cleanup ($script:ran -eq (-not $os.IsServer)) "Incorrect server gate for $name / $script:productType"
}
}
foreach ($script:productType in @(0,4,$null)) { Assert-CleanupThrows { Get-SystemCleanupOS } 'Cannot identify OS' }
function Get-CimInstance { throw 'Synthetic CIM failure' }
Assert-CleanupThrows { Get-SystemCleanupOS } 'Synthetic CIM failure'
}
$serverContext = New-CleanupContext -Server $true
Assert-CleanupThrows { Invoke-SystemCleanupDiskCleanup $serverContext } 'blocked on server'
Assert-CleanupThrows { Invoke-SystemCleanupShadows $serverContext } 'blocked on server'
Assert-CleanupThrows { Invoke-SystemCleanupSearchCompaction $serverContext } 'blocked on server'
$script:serverAssessmentRan=$false
Invoke-SystemCleanupCategory $serverContext 'ShadowCopies' { $script:serverAssessmentRan=$true }
Assert-Cleanup (-not $script:serverAssessmentRan -and -not $serverContext.Stats.ShadowCopies.Enabled -and $serverContext.Stats.ShadowCopies.Status -eq 'Blocked on server' -and $null -eq $serverContext.Stats.ShadowCopies.CandidateBytes) 'A default-disabled server operation must be listed without assessment.'
& {
function Get-CimInstance { param($ClassName) if ($ClassName -eq 'Win32_OperatingSystem') { [pscustomobject]@{ProductType=3; Caption='Fixture Server'} } }
function Invoke-SystemCleanupDiskCleanup { throw 'SERVER GUARD BYPASSED' }
function Invoke-SystemCleanupShadows { throw 'SERVER GUARD BYPASSED' }
function Invoke-SystemCleanupSearchCompaction { throw 'SERVER GUARD BYPASSED' }
function Invoke-SystemCleanupProcess { throw 'SERVER GUARD BYPASSED' }
# Substitute inert actions so the expanded report cannot inspect host paths.
$dispatcher=${function:Invoke-SystemCleanupCategory}
$script:assessed=@()
function Invoke-SystemCleanupCategory {
param($Context,$Name,$Action)
& $dispatcher $Context $Name { $script:assessed += $Name }
}
$o=Get-SystemCleanupOptions
foreach ($key in @($o.Keys)) { if ($o[$key] -is [bool]) { $o[$key]=$false } }
$o.ReportOnly=$true
foreach ($name in $blocked) { if ($name -ne 'DiskCleanup') { $o[$name]=$true } }
$result = @(Invoke-SystemCleanup $o)
Assert-Cleanup ($result.Count -eq 22 -and @($result | Where-Object Status -eq 'Blocked on server').Count -eq $blocked.Count) 'Server report must list every blocked category.'
Assert-Cleanup (@($script:assessed | Where-Object { $_ -in $blocked }).Count -eq 0) 'Server report must not assess blocked categories.'
}
# None is disabled in reports and apply; every nonempty preset remains blocked
# on both server types. No host inventories, registry operations or native calls.
foreach ($server in @($false, $true)) {
foreach ($reportOnly in @($false, $true)) {
foreach ($presetName in $expectedPresets.Keys) {
& {
$CleanupDiskCleanupItems = $presetName
$c = New-CleanupContext -Server $server -ReportOnly $reportOnly
$script:ran = $false
Invoke-SystemCleanupCategory $c 'DiskCleanup' { $script:ran = $true }
$shouldRun = -not $server -and ($reportOnly -or $presetName -ne 'None')
Assert-Cleanup ($script:ran -eq $shouldRun) "Incorrect Disk Cleanup dispatch: $presetName / server=$server / report=$reportOnly"
if ($reportOnly) {
Assert-Cleanup ($c.Stats.DiskCleanup.Enabled -eq ($presetName -ne 'None')) 'Disk Cleanup enablement must follow its selection.'
Assert-Cleanup ($c.Stats.DiskCleanup.Setting -ceq "CleanupDiskCleanupItems=$presetName") 'Report must identify the real operator setting.'
if ($server) { Assert-Cleanup ($c.Stats.DiskCleanup.Status -eq 'Blocked on server') 'Presets must not bypass the server block.' }
}
}
}
}
}
& {
$CleanupDiskCleanupItems = 'None'
$c = New-CleanupContext
function Get-ChildItem { throw 'None must not access the registry.' }
function Test-SystemCleanupAppRunning { throw 'None must not probe native cleanup.' }
function Invoke-SystemCleanupProcess { throw 'None must not launch cleanmgr.' }
$script:messages = @()
Invoke-SystemCleanupCategory $c 'DiskCleanup' { Invoke-SystemCleanupDiskCleanup $c }
Write-SystemCleanupReport $c
$report = $script:messages -join "`n"
Assert-Cleanup ($report -match '(?s)DISABLED -.*DiskCleanup \[CleanupDiskCleanupItems=None\].*No handlers selected') 'None must appear in the disabled report section with a clear explanation.'
Assert-Cleanup ($report -match 'items not selected.*Previous Installations' -and $report -notmatch 'CleanupDiskCleanup=') 'None should report unselected handlers without advertising the removed boolean.'
$c.Options.ReportOnly = $false
Invoke-SystemCleanupDiskCleanup $c
Assert-Cleanup ($c.Errors -eq 0) 'None must not attempt native cleanup, even through the helper directly.'
}
# File ages, literal brackets, nested fresh files, no changes in preview.
$root=Join-Path $testRoot 'temps'
$old=New-CleanupFixture 'temps\old[1].tmp'
$fresh=New-CleanupFixture 'temps\parent\fresh.tmp' 'fresh' 0
$nestedOld=New-CleanupFixture 'temps\parent\old.tmp'
[IO.Directory]::SetLastWriteTimeUtc((Split-Path -Parent $fresh), [datetime]::UtcNow.AddDays(-90))
$cutoff=[datetime]::UtcNow.AddDays(-7)
$c=New-CleanupContext
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
Assert-Cleanup ($c.Stats.SystemTemp.CandidateFiles -eq 2 -and $c.Stats.SystemTemp.RemovedFiles -eq 0) 'Preview counts incorrect.'
Assert-Cleanup ((Test-Path -LiteralPath $old) -and (Test-Path -LiteralPath $nestedOld) -and (Test-Path -LiteralPath $fresh)) 'Preview changed files.'
$c=New-CleanupContext -ReportOnly $false
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
Assert-Cleanup (-not (Test-Path -LiteralPath $old) -and -not (Test-Path -LiteralPath $nestedOld) -and (Test-Path -LiteralPath $fresh)) 'Age/leaf deletion failure.'
Assert-Cleanup ($c.Stats.SystemTemp.RemovedFiles -eq 2) 'Removed files were not counted.'
# Disabled categories get independent report estimates, even when files overlap an
# enabled category later in the run. Apply mode still ignores disabled categories.
$potentialRoot=Join-Path $testRoot 'potential'
$potentialOriginal=New-CleanupFixture 'potential\install.exe' 'abc'
$potentialDuplicate=New-CleanupFixture 'potential\install (1).exe' 'abc'
$potentialRecent=New-CleanupFixture 'potential\recent.exe' 'fresh' 0
$c=New-CleanupContext
$c.Options.DownloadedExecutables=$false; $c.Options.DuplicateDownloads=$true
Invoke-SystemCleanupCategory $c 'DownloadedExecutables' { Clear-SystemCleanupTree $c 'DownloadedExecutables' $potentialRoot $cutoff -Include @('*.exe') }
Invoke-SystemCleanupCategory $c 'DuplicateDownloads' { Remove-SystemCleanupDuplicates $c $potentialRoot $cutoff }
Assert-Cleanup (-not $c.Stats.DownloadedExecutables.Enabled -and $c.Stats.DownloadedExecutables.CandidateFiles -eq 2 -and $c.Stats.DownloadedExecutables.CandidateBytes -eq 6) 'Disabled download estimate is missing or includes recent files.'
Assert-Cleanup ($c.Stats.DuplicateDownloads.Enabled -and $c.Stats.DuplicateDownloads.CandidateFiles -eq 1 -and $c.Stats.DuplicateDownloads.CandidateBytes -eq 3) 'Disabled preview consumed an enabled category candidate.'
Assert-Cleanup (-not $c.Options.DownloadedExecutables -and (Test-Path -LiteralPath $potentialDuplicate)) 'Preview enabled a disabled option or deleted data.'
$totals=Get-SystemCleanupReportTotals $c
Assert-Cleanup ($totals.EnabledBytes -eq 3 -and $totals.EnabledFiles -eq 1 -and $totals.AdditionalDisabledBytes -eq 3 -and $totals.AdditionalDisabledFiles -eq 1) 'Overlapping report totals double-counted a file.'
$script:messages=@()
Write-SystemCleanupReport $c
$report=$script:messages -join "`n"
Assert-Cleanup ($report.IndexOf('ENABLED -') -lt $report.IndexOf('DISABLED -') -and $report.IndexOf('DuplicateDownloads [CleanupDuplicateDownloads=true]') -lt $report.IndexOf('DISABLED -') -and $report.IndexOf('DownloadedExecutables [CleanupDownloadedExecutables=false]') -gt $report.IndexOf('DISABLED -')) 'Enabled and disabled report groups are unclear or misplaced.'
$c=New-CleanupContext -ReportOnly $false
$script:disabledRan=$false
Invoke-SystemCleanupCategory $c 'DownloadedExecutables' { $script:disabledRan=$true; Clear-SystemCleanupTree $c 'DownloadedExecutables' $potentialRoot $cutoff -Include @('*.exe') }
Assert-Cleanup (-not $script:disabledRan -and (Test-Path -LiteralPath $potentialOriginal) -and (Test-Path -LiteralPath $potentialDuplicate) -and (Test-Path -LiteralPath $potentialRecent)) 'Apply mode ran a disabled category.'
$outside=New-CleanupFixture 'outside\preserved.tmp'
Assert-Cleanup (-not (Test-SystemCleanupPath $outside $root)) 'Containment check accepted an outside file.'
Assert-Cleanup (-not (Test-SystemCleanupPath 'C:\Windows' 'C:\')) 'Drive-root cleanup must be rejected.'
$junction=Join-Path $root 'linked'
$null=New-Item -ItemType Junction -Path $junction -Target (Split-Path -Parent $outside)
try {
Assert-Cleanup (-not (Test-SystemCleanupPath (Join-Path $junction 'preserved.tmp') $root)) 'Linked ancestor was accepted.'
$c=New-CleanupContext -ReportOnly $false
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
Assert-Cleanup (Test-Path -LiteralPath $outside) 'Cleanup followed junction outside the target.'
} finally { [IO.Directory]::Delete($junction, $false) }
$locked=New-CleanupFixture 'temps\locked.tmp'
$lock=[IO.File]::Open($locked, 'Open', 'ReadWrite', 'None')
try {
$c=New-CleanupContext -ReportOnly $false
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
Assert-Cleanup ((Test-Path -LiteralPath $locked) -and $c.Stats.SystemTemp.FailedFiles -eq 1) 'Locked files must be retained and counted.'
} finally { $lock.Dispose() }
# Same length is not the same content, and extensions must match.
$null=New-CleanupFixture 'downloads\a.txt' 'abc'
$same=New-CleanupFixture 'downloads\a (1).txt' 'abc'
$different=New-CleanupFixture 'downloads\a (2).txt' 'xyz'
$extension=New-CleanupFixture 'downloads\a (1).csv' 'abc'
$recent=New-CleanupFixture 'downloads\a (3).txt' 'abc' 0
$c=New-CleanupContext -ReportOnly $false; $c.Options.DuplicateDownloads=$true
Invoke-SystemCleanupCategory $c 'DuplicateDownloads' { Remove-SystemCleanupDuplicates $c (Join-Path $testRoot 'downloads') $cutoff }
Assert-Cleanup (-not (Test-Path -LiteralPath $same) -and (Test-Path -LiteralPath $different) -and (Test-Path -LiteralPath $extension) -and (Test-Path -LiteralPath $recent)) 'Duplicate matching/retention failure.'
# Entire backup retained when a nested file is recent; old complete unit removed.
$backupOld=New-CleanupFixture 'backups\phone\old.dat'
$backupFresh=New-CleanupFixture 'backups\phone\nested\new.dat' 'new' 0
$bundle=Split-Path -Parent $backupOld
[IO.Directory]::SetLastWriteTimeUtc($bundle, [datetime]::UtcNow.AddDays(-60))
$c=New-CleanupContext -ReportOnly $false; $c.Options.ITunesBackups=$true
Invoke-SystemCleanupCategory $c 'ITunesBackups' { Remove-SystemCleanupBundle $c 'ITunesBackups' $bundle $cutoff }
Assert-Cleanup ((Test-Path -LiteralPath $backupOld) -and (Test-Path -LiteralPath $backupFresh)) 'Recent backup was partially cleaned.'
[IO.File]::SetLastWriteTimeUtc($backupFresh,[datetime]::UtcNow.AddDays(-60))
[IO.Directory]::SetLastWriteTimeUtc((Split-Path -Parent $backupFresh),[datetime]::UtcNow.AddDays(-60))
$backupLock=[IO.File]::Open($backupFresh,'Open','ReadWrite','None')
try {
$c=New-CleanupContext -ReportOnly $false; $c.Options.ITunesBackups=$true
Invoke-SystemCleanupCategory $c 'ITunesBackups' { Remove-SystemCleanupBundle $c 'ITunesBackups' $bundle $cutoff }
Assert-Cleanup ((Test-Path -LiteralPath $backupOld) -and (Test-Path -LiteralPath $backupFresh)) 'Locked backup was partially cleaned.'
} finally { $backupLock.Dispose() }
$c=New-CleanupContext -ReportOnly $false; $c.Options.ITunesBackups=$true
Invoke-SystemCleanupCategory $c 'ITunesBackups' { Remove-SystemCleanupBundle $c 'ITunesBackups' $bundle $cutoff }
Assert-Cleanup (-not (Test-Path -LiteralPath $bundle)) 'Old backup unit was not completely removed.'
# $I metadata controls retention, NOT the payload's old modification time.
$recycle=Join-Path $testRoot 'recycle'
foreach ($case in @(@{Id='old'; Days=60; Version=2},@{Id='recent'; Days=0; Version=1},@{Id='unknown'; Days=60; Version=99})) {
$meta=New-CleanupFixture ('recycle\S-1-5-21-fixture\$I'+$case.Id) 'placeholder'
$null=New-CleanupFixture ('recycle\S-1-5-21-fixture\$R'+$case.Id) 'data'
$originalPath=[Text.Encoding]::Unicode.GetBytes("C:\fixture.txt`0")
$length=if ($case.Version -eq 1) {544} else {28+$originalPath.Length}
$bytes=New-Object byte[] $length
[BitConverter]::GetBytes([long]$case.Version).CopyTo($bytes,0)
[BitConverter]::GetBytes([long]4).CopyTo($bytes,8)
[BitConverter]::GetBytes([datetime]::UtcNow.AddDays(-$case.Days).ToFileTimeUtc()).CopyTo($bytes,16)
if ($case.Version -eq 1) { $originalPath.CopyTo($bytes,24) }
else {
[BitConverter]::GetBytes([uint32]($originalPath.Length/2)).CopyTo($bytes,24)
$originalPath.CopyTo($bytes,28)
}
[IO.File]::WriteAllBytes($meta,$bytes)
}
$c=New-CleanupContext -ReportOnly $false; $c.Options.RecycleBin=$true
Invoke-SystemCleanupCategory $c 'RecycleBin' { Clear-SystemCleanupRecycleBin $c $recycle $cutoff }
Assert-Cleanup (-not (Test-Path -LiteralPath (Join-Path $recycle 'S-1-5-21-fixture\$Rold')) -and -not (Test-Path -LiteralPath (Join-Path $recycle 'S-1-5-21-fixture\$Iold'))) 'Old recycled pair not removed.'
foreach ($id in @('recent','unknown')) {
Assert-Cleanup ((Test-Path -LiteralPath (Join-Path $recycle ('S-1-5-21-fixture\$I'+$id))) -and (Test-Path -LiteralPath (Join-Path $recycle ('S-1-5-21-fixture\$R'+$id)))) "Unsafe recycle deletion: $id"
}
$truncated=New-CleanupFixture 'truncated-recycle-metadata' 'data'
[IO.File]::WriteAllBytes($truncated, [byte[]]@(2,0,0,0,0,0,0,0))
Assert-CleanupThrows { Get-SystemCleanupRecycleDate $truncated } 'Truncated'
# Native failure is observable; preview never starts a process.
& {
$script:starts=0
function Start-Process { param($FilePath,$ArgumentList,$WindowStyle,[switch]$Wait,[switch]$PassThru)
$script:starts++; Assert-Cleanup ($Wait -and $PassThru -and $WindowStyle -eq 'Hidden') 'Native operations must wait, capture exit status, and hide the window.'
[pscustomobject]@{ExitCode=5}
}
$c=New-CleanupContext
Invoke-SystemCleanupProcess $c 'powercfg.exe' '/hibernate off'
Assert-Cleanup ($script:starts -eq 0) 'Report mode launched a native process.'
$c.Options.ReportOnly=$false
Assert-CleanupThrows { Invoke-SystemCleanupProcess $c 'powercfg.exe' '/hibernate off' } 'exit code 5'
}
# cleanmgr only writes selected handlers in an unused slot; finally restores after failure.
& {
$script:events=@(); $script:nativeFailure=$false
function Test-SystemCleanupAppRunning { return $false }
function Get-ChildItem {
param($LiteralPath)
foreach ($name in @('Thumbnail Cache','Previous Installations')) {
$key=[pscustomobject]@{PSChildName=$name; PSPath=('fixture:\'+$name)}
$key | Add-Member ScriptMethod GetValueNames { @('StateFlags1000') }
$key
}
}
function New-ItemProperty { param($LiteralPath,$Name,$Value,$PropertyType) $script:events += "write:$LiteralPath/$Name=$Value" }
function Remove-ItemProperty { param($LiteralPath,$Name) $script:events += "remove:$LiteralPath/$Name" }
function Invoke-SystemCleanupProcess { param($Context,$FileName,$Arguments) $script:events += "run:$FileName $Arguments"; if ($script:nativeFailure) { throw 'Synthetic native failure' } }
$c=New-CleanupContext; $c.Options.DiskCleanupItems=@('Thumbnail Cache'); $c.Options.DiskCleanupPreset='Custom'
Invoke-SystemCleanupDiskCleanup $c
Assert-Cleanup ($script:events.Count -eq 0) 'Report mode wrote Disk Cleanup settings.'
$c.Options.ReportOnly=$false
foreach ($script:nativeFailure in @($false,$true)) {
$script:events=@()
if ($script:nativeFailure) { Assert-CleanupThrows { Invoke-SystemCleanupDiskCleanup $c } 'Synthetic native failure' }
else { Invoke-SystemCleanupDiskCleanup $c }
Assert-Cleanup ($script:events.Count -eq 3 -and $script:events[0] -eq 'write:fixture:\Thumbnail Cache/StateFlags1001=2' -and $script:events[1] -eq 'run:cleanmgr.exe /sagerun:1001' -and $script:events[2] -eq 'remove:fixture:\Thumbnail Cache/StateFlags1001') 'Disk Cleanup settings selection/restoration failed.'
}
}
# Snapshot deletion is exact-ID based and retains the newest system-volume snapshot.
& {
$script:commands=@()
function Get-CimInstance {
param($ClassName)
if ($ClassName -eq 'Win32_Volume') { [pscustomobject]@{DriveLetter=$env:SystemDrive; DeviceID='volume1'} }
else {
[pscustomobject]@{VolumeName='volume1'; InstallDate=[datetime]'2026-10-01'; ID='{11111111-1111-1111-1111-111111111111}'}
[pscustomobject]@{VolumeName='volume1'; InstallDate=[datetime]'2026-10-02'; ID='{22222222-2222-2222-2222-222222222222}'}
[pscustomobject]@{VolumeName='volume2'; InstallDate=[datetime]'2026-09-01'; ID='{33333333-3333-3333-3333-333333333333}'}
}
}
function Invoke-SystemCleanupProcess { param($Context,$FileName,$Arguments) $script:commands += "$FileName $Arguments" }
Invoke-SystemCleanupShadows (New-CleanupContext)
Assert-Cleanup ($script:commands.Count -eq 1 -and $script:commands[0] -match '/Shadow=\{11111111-' -and $script:commands[0] -notmatch '/Oldest') 'Incorrect VSS target selection.'
}
# Search always restores running state after failure, never changes startup settings.
& {
$savedProgramData=$env:ProgramData
$null=New-CleanupFixture 'search\Microsoft\Search\Data\Applications\Windows\Windows.edb'
try {
$env:ProgramData=Join-Path $testRoot 'search'
$script:serviceEvents=@()
function Get-Service {
param($Name)
$s=[pscustomobject]@{Status=$script:originalServiceStatus}
$s | Add-Member ScriptMethod WaitForStatus { param($Status,$Timeout) $script:serviceEvents += 'wait' }
return $s
}
function Stop-Service { param($Name) $script:serviceEvents += 'stop' }
function Start-Service { param($Name) $script:serviceEvents += 'start' }
function Set-Service { throw 'Startup configuration must be preserved.' }
function Invoke-SystemCleanupProcess { param($Context,$FileName,$Arguments) $script:serviceEvents += 'compact'; throw 'Synthetic compaction failure' }
foreach ($script:originalServiceStatus in @('Running','Stopped')) {
$script:serviceEvents=@()
$c=New-CleanupContext -ReportOnly $false
Assert-CleanupThrows { Invoke-SystemCleanupSearchCompaction $c } 'Synthetic compaction failure'
$expected=if ($script:originalServiceStatus -eq 'Running') { 'stop,wait,compact,start' } else { 'compact' }
Assert-Cleanup (($script:serviceEvents -join ',') -eq $expected) 'Search service restoration failed.'
}
$script:serviceEvents=@()
Invoke-SystemCleanupSearchCompaction (New-CleanupContext)
Assert-Cleanup ($script:serviceEvents.Count -eq 0) 'Preview changed Search service state.'
} finally { $env:ProgramData=$savedProgramData }
}
# Entire entry point with mixed enablement in preview. All mutation APIs fail
# the test if called. Every environment path and inventory points at inert fixtures.
& {
$savedEnvironment=@{SystemRoot=$env:SystemRoot; SystemDrive=$env:SystemDrive; ProgramData=$env:ProgramData}
$previewRoot=Join-Path $testRoot 'preview'
$null=New-CleanupFixture 'preview\Windows\Temp\old.tmp'
$null=New-CleanupFixture 'preview\Windows\Temp\CbsPersist_fixture.log'
$null=New-CleanupFixture 'preview\Users\Alice\AppData\Local\Temp\old.tmp'
$null=New-CleanupFixture 'preview\Users\Alice\Downloads\install.exe'
$null=New-CleanupFixture 'preview\hiberfil.sys'
foreach ($exe in @('powercfg.exe','schtasks.exe','esentutl.exe','vssadmin.exe','cleanmgr.exe')) { $null=New-CleanupFixture ('preview\Windows\System32\'+$exe) 'inert, never executed' }
try {
$env:SystemRoot=Join-Path $previewRoot 'Windows'; $env:SystemDrive=$previewRoot
$env:ProgramData=Join-Path $previewRoot 'ProgramData'
function Get-CimInstance {
param($ClassName)
switch ($ClassName) {
Win32_OperatingSystem { [pscustomobject]@{ProductType=1; Caption='Fixture Client'} }
Win32_UserProfile { [pscustomobject]@{Special=$false; LocalPath=(Join-Path $previewRoot 'Users\Alice')} }
Win32_Volume { [pscustomobject]@{DriveLetter=$env:SystemDrive; DeviceID='volume1'} }
Win32_ShadowCopy {
[pscustomobject]@{VolumeName='volume1'; InstallDate=[datetime]'2026-10-01'; ID='{11111111-1111-1111-1111-111111111111}'}
[pscustomobject]@{VolumeName='volume1'; InstallDate=[datetime]'2026-10-02'; ID='{22222222-2222-2222-2222-222222222222}'}
}
}
}
function Test-SystemCleanupAppRunning { return $false }
function Get-Service { [pscustomobject]@{Status='Stopped'} }
function Remove-Item { throw 'PREVIEW MUTATION: Remove-Item' }
function New-ItemProperty { throw 'PREVIEW MUTATION: registry write' }
function Remove-ItemProperty { throw 'PREVIEW MUTATION: registry removal' }
function Start-Service { throw 'PREVIEW MUTATION: start service' }
function Stop-Service { throw 'PREVIEW MUTATION: stop service' }
function Delete-DeliveryOptimizationCache { throw 'PREVIEW MUTATION: delivery cache' }
function Start-Process { throw 'PREVIEW MUTATION: native program' }
$o=Get-SystemCleanupOptions
$result=@(Invoke-SystemCleanup $o)
Assert-Cleanup ($result.Count -eq 22 -and @($result | Where-Object Status -ne 'Preview').Count -eq 0) "Full preview did not cover every category (count=$($result.Count))."
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'DownloadedExecutables' -and -not $_.Enabled -and $_.CandidateFiles -eq 1 }).Count -eq 1) 'Default-disabled downloads were not assessed by the entry point.'
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'ComponentStore' -and -not $_.Enabled -and $null -eq $_.CandidateBytes -and $_.EstimateStatus -eq 'Not estimated' }).Count -eq 1) 'Unknown native savings must not be reported as zero.'
Assert-Cleanup (Test-Path -LiteralPath (Join-Path $env:SystemRoot 'Temp\old.tmp')) 'Full preview removed a fixture.'
function Test-SystemCleanupAppRunning { return $true }
function Get-Command { return $null }
$o.DiskCleanupItems=@(); $o.DiskCleanupPreset='None'
$result=@(Invoke-SystemCleanup $o)
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'RevitJournals' -and $_.Status -eq 'Skipped' }).Count -eq 1) 'An active application should skip cleanup, not fail the whole run.'
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'DeliveryOptimization' -and -not $_.Enabled -and $_.Status -eq 'Unavailable' -and $null -eq $_.CandidateBytes }).Count -eq 1) 'A missing optional feature must be reported as unavailable, not zero savings or a failed report.'
} finally {
$env:SystemRoot=$savedEnvironment.SystemRoot; $env:SystemDrive=$savedEnvironment.SystemDrive; $env:ProgramData=$savedEnvironment.ProgramData
}
}
Write-Host "PASS: $script:assertions offline cleanup assertions ($($PSVersionTable.PSVersion))."
} finally {
# Only this test's generated directory; links are removed non-recursively above.
$resolved=[IO.Path]::GetFullPath($testRoot)
$expectedParent=[IO.Path]::GetFullPath($env:TEMP).TrimEnd('\')+'\'
if (-not $resolved.StartsWith($expectedParent,[StringComparison]::OrdinalIgnoreCase) -or (Split-Path -Leaf $resolved) -notmatch '^SystemCleanupTests-[0-9a-f]{32}$') { throw 'Unsafe fixture cleanup path.' }
if (Test-Path -LiteralPath $resolved) { Remove-Item -LiteralPath $resolved -Recurse -Force }
}