improve detection of space savings

This commit is contained in:
2026-10-23 11:22:55 -04:00
parent ec9141d062
commit c5ef81dfca
4 changed files with 181 additions and 7 deletions
+73 -1
View File
@@ -7,6 +7,7 @@ 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.
It also reports hibernation/VSS usage and notes potential component-store savings without running DISM analysis.
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.
@@ -315,11 +316,79 @@ function Get-SystemCleanupReportTotals {
}
}
function Get-SystemCleanupVolumeId {
param($Reference)
# CIM references can be embedded instances or escaped WMI object-path strings.
$text = if ($Reference -is [string]) { $Reference } elseif ($Reference.DeviceID) { [string]$Reference.DeviceID } else { [string]$Reference }
$match = [regex]::Match($text, '(?i)Volume\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}')
if (-not $match.Success) { throw 'Cannot identify the volume in a shadow-storage reference.' }
return $match.Value.ToLowerInvariant()
}
function Get-SystemCleanupShadowStorageDiagnostic {
$volumes = @(Get-CimInstance -ClassName Win32_Volume -ErrorAction Stop)
$systemVolume = @($volumes | Where-Object { $_.DriveLetter -eq $env:SystemDrive })
if ($systemVolume.Count -ne 1) { throw 'Cannot uniquely identify the system volume.' }
$systemId = Get-SystemCleanupVolumeId $systemVolume[0]
$storage = @(Get-CimInstance -ClassName Win32_ShadowStorage -ErrorAction Stop | Where-Object {
(Get-SystemCleanupVolumeId $_.Volume) -eq $systemId
})
if (-not $storage.Count) { return "for $env:SystemDrive - no shadow-storage association" }
$used = [decimal]0; $allocated = [decimal]0; $locations = @()
foreach ($item in $storage) {
# A missing measurement must not be converted to zero.
foreach ($property in @('UsedSpace', 'AllocatedSpace')) {
$bytes = [uint64]0
if (-not [uint64]::TryParse([string]$item.$property, [ref]$bytes)) { throw "Invalid shadow-storage $property." }
if ($property -eq 'UsedSpace') { $used += $bytes } else { $allocated += $bytes }
}
$targetId = Get-SystemCleanupVolumeId $item.DiffVolume
$target = @($volumes | Where-Object { (Get-SystemCleanupVolumeId $_) -eq $targetId })
$locations += if ($target.Count -eq 1 -and $target[0].DriveLetter) { $target[0].DriveLetter } else { 'unmounted/unknown volume' }
}
return ('for {0} - {1:N2} GiB used / {2:N2} GiB allocated; stored on {3}' -f $env:SystemDrive, ($used / 1GB), ($allocated / 1GB), (($locations | Select-Object -Unique) -join ', '))
}
function Get-SystemCleanupDiagnostics {
param($Context)
$diagnostics = [ordered]@{}
if (-not $Context.Options.ReportOnly) { return $diagnostics }
if ($Context.OS.IsServer) {
$diagnostics.Hibernation = 'not assessed (server policy)'
$diagnostics.ShadowStorage = 'not assessed (server policy)'
} else {
try {
$path = Join-Path $env:SystemDrive 'hiberfil.sys'
$file = Get-Item -LiteralPath $path -Force -ErrorAction Stop
if ($file.PSIsContainer -or ($file.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Unexpected hibernation file type.' }
$diagnostics.Hibernation = '{0}: {1:N2} GiB file size' -f $path, ($file.Length / 1GB)
} catch [System.Management.Automation.ItemNotFoundException] {
$diagnostics.Hibernation = 'hiberfil.sys not present'
} catch {
Write-SystemCleanupMessage "Hibernation diagnostic: $($_.Exception.Message)" -Detail
$diagnostics.Hibernation = 'unavailable (file inspection failed; see verbose)'
}
try { $diagnostics.ShadowStorage = Get-SystemCleanupShadowStorageDiagnostic } catch {
Write-SystemCleanupMessage "Shadow-storage diagnostic: $($_.Exception.Message)" -Detail
$diagnostics.ShadowStorage = 'unavailable (storage inspection failed; see verbose)'
}
}
# Avoid slow DISM analysis during previews; potential savings are not measured.
$diagnostics.ComponentStore = 'not analyzed; removing superseded updates may free substantial space, or little/none.'
return $diagnostics
}
function Write-SystemCleanupReport {
param($Context)
Write-SystemCleanupMessage 'REPORT ONLY - no cleanup performed.'
$totals = Get-SystemCleanupReportTotals $Context
Write-SystemCleanupMessage ('Known savings: ENABLED {0:N2} MiB ({1:N0} files); additional DISABLED {2:N2} MiB ({3:N0} files).' -f ($totals.EnabledBytes / 1MB), $totals.EnabledFiles, ($totals.AdditionalDisabledBytes / 1MB), $totals.AdditionalDisabledFiles)
if ($Context.ContainsKey('Diagnostics') -and $Context.Diagnostics.Count) {
Write-SystemCleanupMessage 'DIAGNOSTICS - current usage/potential, excluded from savings totals'
foreach ($entry in $Context.Diagnostics.GetEnumerator()) {
Write-SystemCleanupMessage (" {0}: {1}" -f $entry.Key, $entry.Value)
}
}
Write-SystemCleanupMessage "Retention: temp $($Context.Options.TempDays)d; diagnostics $($Context.Options.DiagnosticDays)d; backups $($Context.Options.BackupDays)d."
Write-SystemCleanupMessage ('{0,-25} {1,8} {2,11} {3}' -f 'Category', 'Files', 'MiB', 'Notes')
foreach ($group in @('Enabled', 'Disabled', 'Blocked')) {
@@ -747,7 +816,10 @@ function Invoke-SystemCleanup {
Write-SystemCleanupMessage 'Component cleanup runs asynchronously under Task Scheduler; completion and reclaimed bytes are not measured here.' -Detail:$Options.ReportOnly
}
Invoke-SystemCleanupCategory $context 'DiskCleanup' { Invoke-SystemCleanupDiskCleanup $context }
if ($Options.ReportOnly) { Write-SystemCleanupReport $context }
if ($Options.ReportOnly) {
$context.Diagnostics = Get-SystemCleanupDiagnostics $context
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 {
+39 -6
View File
@@ -32,7 +32,7 @@ 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 compact
report starts with the unique enabled savings and additional disabled savings,
then lists every category once in three sections:
followed by three diagnostic lines, then every category once in 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
@@ -58,6 +58,32 @@ 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.
The report-only diagnostics run regardless of the corresponding cleanup flags:
- **Hibernation:** current system-drive `hiberfil.sys` size in GiB, or explicitly
"not present". An inspection failure is unavailable, not an absent file.
- **ShadowStorage:** used and allocated GiB for the system volume's shadow-storage
association, including the drive where that data resides. Storage on another
drive is labeled accordingly; it does not represent space occupied on C:.
No registered association and failed/unsupported CIM queries are distinguished.
- **ComponentStore:** a short note that removing superseded updates may free
substantial space, or little/none. The component store is not analyzed, and no
Yes/No recommendation or package count is calculated. The note appears even if
`CleanupComponentStore=false` or `CleanupDiskCleanupItems=None`.
These are **current usage and potential, not extra reclaimable bytes**;
they are excluded from both savings totals. VSS data may be shared between
snapshots, and the script retains the newest snapshot. Hibernation/VSS diagnostics
remain unassessed on servers under the existing server policy. The component-store
note appears on both clients and servers. Diagnostics are skipped in
apply mode and require no new Syncro variables.
Report mode does not launch DISM analysis, avoiding its additional runtime on slow
endpoints. Component cleanup removes superseded updates, so potential savings
depend on accumulated updates and previous Windows maintenance. A large WinSxS
folder alone does not indicate how much is reclaimable. Actual cleanup still uses
the existing background task when `CleanupComponentStore=true` in apply mode.
The default output is designed for Syncro's limited script output: one line per
category, including zero results, without a second PowerShell object dump or
per-category progress chatter. Column sizes are in MiB; positive sizes below
@@ -74,10 +100,11 @@ Syncro variable is required. The `Invoke-SystemCleanup` function still returns
structured results for programmatic callers; the script entry suppresses their
automatic formatting after printing the human-readable report.
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.
Report mode performs no cleanup, changes no cleanup registry settings, stops no
services, launches no native programs, and requests no 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 from these usage measurements alone.
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
@@ -230,9 +257,15 @@ totals for overlapping categories, and disabled categories remaining untouched i
apply mode. Preset tests verify exact handler membership, cumulative selections,
RMM scope preservation, None disabling native work, and the server exclusions.
Output tests cover the duplicate-object regression, a 22-category preview under
4 KiB, separate enabled/disabled sections, and preservation of diagnostic notes.
4 KiB including diagnostics, separate enabled/disabled sections, and preservation
of diagnostic notes. Regression checks ensure DISM analysis is absent and report
diagnostics launch no native programs.
Hibernation/VSS tests cover absence, access failures, cross-drive storage, server
exclusions, and usage staying out of savings totals.
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),
[component analysis](https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/determine-the-actual-size-of-the-winsxs-folder?view=windows-11),
[shadow-storage measurements](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/vsswmi/win32-shadowstorage),
[Windows Search](https://learn.microsoft.com/troubleshoot/windows-client/shell-experience/windows-search-performance-issues).
+3
View File
@@ -40,6 +40,9 @@
# Every variable configured in Syncro needs a nonempty value.
# Report-only assesses enabled AND disabled categories in separate report sections.
# Compact output shows totals first and one row per category; no duplicate object dump.
# Report-only adds hibernation/VSS usage and a note about potential component-store savings.
# Usage is excluded from savings. Hibernation/VSS remain unassessed on servers.
# Reports do not run DISM analysis; savings from superseded updates are not estimated.
# For full diagnostics, set $VerbosePreference = 'Continue' before Run-Script.
# Verbose output can exceed Syncro's output limit. No new Syncro variables are needed.
# Server-blocked categories are listed without assessment. Native savings may be unknown.
+66
View File
@@ -30,6 +30,7 @@ function New-CleanupFixture {
try {
$core = Read-CleanupAst 'Start-SystemCleanup.ps1'
$shim = Read-CleanupAst 'rmm/Start-SystemCleanup.ps1'
Assert-Cleanup ($core.Extent.Text -notmatch '(?i)AnalyzeComponentStore|dism\.exe') 'Reports must not ship a DISM analysis invocation.'
foreach ($definition in $core.FindAll({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst]}, $false)) {
. ([scriptblock]::Create($definition.Extent.Text))
}
@@ -250,6 +251,70 @@ try {
Assert-Cleanup ($c.Errors -eq 0) 'None must not attempt native cleanup, even through the helper directly.'
}
# Report diagnostics remain independent of enablement and never inflate savings.
& {
$script:fileReads=0; $script:storageReads=0; $script:diagnosticProcesses=0
function Start-Process { $script:diagnosticProcesses++; throw 'Report diagnostics must not launch native programs.' }
$script:hiberState='present'; $script:storageState='present'
$sourceId='\\?\Volume{11111111-1111-1111-1111-111111111111}\'
$otherId='\\?\Volume{22222222-2222-2222-2222-222222222222}\'
$script:storageTarget=$sourceId
function Get-Item {
param($LiteralPath)
$script:fileReads++
if ($script:hiberState -eq 'missing') { throw [Management.Automation.ItemNotFoundException]::new('fixture absent') }
if ($script:hiberState -eq 'denied') { throw [UnauthorizedAccessException]::new('fixture denied') }
[pscustomobject]@{Length=4GB; PSIsContainer=$false; Attributes=[IO.FileAttributes]::Hidden}
}
function Get-CimInstance {
param($ClassName)
$script:storageReads++
if ($script:storageState -eq 'denied') { throw 'Synthetic CIM access failure' }
if ($ClassName -eq 'Win32_Volume') {
[pscustomobject]@{DeviceID=$sourceId; DriveLetter=$env:SystemDrive}
[pscustomobject]@{DeviceID=$otherId; DriveLetter='Z:'}
} elseif ($ClassName -eq 'Win32_ShadowStorage' -and $script:storageState -ne 'empty') {
# Source as escaped WMI path; destination as embedded CIM-style object.
[pscustomobject]@{Volume='Win32_Volume.DeviceID="\\\\?\\Volume{11111111-1111-1111-1111-111111111111}\\"'; DiffVolume=[pscustomobject]@{DeviceID=$script:storageTarget}; UsedSpace=$(if ($script:storageState -eq 'invalid') { $null } else { 2GB }); AllocatedSpace=3GB}
[pscustomobject]@{Volume=[pscustomobject]@{DeviceID=$otherId}; DiffVolume=[pscustomobject]@{DeviceID=$otherId}; UsedSpace=99GB; AllocatedSpace=100GB}
}
}
$c=New-CleanupContext
foreach ($name in @('DisableHibernation','ShadowCopies','ComponentStore')) {
$c.Options[$name]=$false
Invoke-SystemCleanupCategory $c $name {}
}
$c.Diagnostics=Get-SystemCleanupDiagnostics $c
Assert-Cleanup ($c.Diagnostics.Hibernation -match '4.00 GiB file size' -and $c.Diagnostics.ShadowStorage -match '2.00 GiB used / 3.00 GiB allocated' -and $c.Diagnostics.ComponentStore -match 'not analyzed;.*superseded updates.*substantial.*little/none') 'Disabled options must still receive usage diagnostics and an honest note about potential component-store savings.'
Assert-Cleanup ($c.Diagnostics.ShadowStorage -notmatch '99.00|100.00' -and $c.Diagnostics.ShadowStorage.EndsWith("stored on $env:SystemDrive")) 'VSS must select the system volume and report its actual storage location.'
$totals=Get-SystemCleanupReportTotals $c
Assert-Cleanup ($totals.EnabledBytes -eq 0 -and $totals.AdditionalDisabledBytes -eq 0 -and -not $c.Options.ShadowCopies -and $c.Errors -eq 0) 'Diagnostic usage is not reclaimable savings and must not enable cleanup.'
$script:messages=@()
Write-SystemCleanupReport $c
$report=$script:messages -join "`n"
Assert-Cleanup ($report -match 'DIAGNOSTICS - current usage/potential, excluded from savings totals' -and [regex]::Matches($report,'(?m)^ (Hibernation|ShadowStorage|ComponentStore):').Count -eq 3) 'Diagnostics must occupy three compact lines outside category totals.'
$c.Options.ComponentStore=$true
$d=Get-SystemCleanupDiagnostics $c
Assert-Cleanup ($script:diagnosticProcesses -eq 0 -and $d.ComponentStore -eq $c.Diagnostics.ComponentStore) 'Enabling component cleanup must not launch analysis or fabricate a measured recommendation in report mode.'
$script:storageTarget=$otherId
Assert-Cleanup ((Get-SystemCleanupShadowStorageDiagnostic) -match 'stored on Z:') 'Shadow storage on another drive must not be attributed to the system drive.'
$script:storageState='empty'; $script:hiberState='missing'
$d=Get-SystemCleanupDiagnostics $c
Assert-Cleanup ($d.Hibernation -eq 'hiberfil.sys not present' -and $d.ShadowStorage -match 'no shadow-storage association') 'Absent hibernation or VSS data must be reported explicitly.'
$script:storageState='invalid'
Assert-Cleanup ((Get-SystemCleanupDiagnostics $c).ShadowStorage -match 'unavailable') 'Missing VSS measurements must not become zero.'
$script:storageState='denied'; $script:hiberState='denied'
$d=Get-SystemCleanupDiagnostics $c
Assert-Cleanup ($d.Hibernation -match 'unavailable' -and $d.ShadowStorage -match 'unavailable' -and $d.ComponentStore -match 'not analyzed' -and $c.Errors -eq 0) 'A diagnostic failure must not prevent the other diagnostics or fail cleanup reporting.'
$script:fileReads=0; $script:storageReads=0
$c.OS.IsServer=$true
$d=Get-SystemCleanupDiagnostics $c
Assert-Cleanup ($script:fileReads -eq 0 -and $script:storageReads -eq 0 -and $script:diagnosticProcesses -eq 0 -and $d.Hibernation -match 'server policy' -and $d.ShadowStorage -match 'server policy' -and $d.ComponentStore -match 'not analyzed') 'Server reports must block hibernation/VSS assessment and only note potential component-store savings.'
$c.Options.ReportOnly=$false
$d=Get-SystemCleanupDiagnostics $c
Assert-Cleanup ($d.Count -eq 0 -and $script:fileReads -eq 0 -and $script:storageReads -eq 0 -and $script:diagnosticProcesses -eq 0) 'Apply mode must not run report diagnostics.'
}
# File ages, literal brackets, nested fresh files, no changes in preview.
$root=Join-Path $testRoot 'temps'
$old=New-CleanupFixture 'temps\old[1].tmp'
@@ -502,6 +567,7 @@ try {
}
Assert-Cleanup ($compactOutput -notmatch 'Assessing |selected items:|items not selected|CandidateFiles\s*:' -and $compactOutput -match 'Standard \(7 handlers\)') 'Default output must show the preset without progress chatter, handler inventories, or object dumps.'
Assert-Cleanup (($script:details -join "`n") -match 'items not selected.*Previous Installations') 'Full handler details must remain available in verbose output.'
Assert-Cleanup ($compactOutput -match 'Hibernation: .*file size' -and $compactOutput -match 'ShadowStorage:' -and $compactOutput -match 'ComponentStore: not analyzed;.*superseded updates.*substantial.*little/none') 'Full entry-point report must include usage and potential savings notes even with cleanup disabled.'
function Test-SystemCleanupAppRunning { return $true }
function Get-Command { return $null }
$o.DiskCleanupItems=@(); $o.DiskCleanupPreset='None'