diff --git a/Start-SystemCleanup.ps1 b/Start-SystemCleanup.ps1 index 6c87976..d631232 100644 --- a/Start-SystemCleanup.ps1 +++ b/Start-SystemCleanup.ps1 @@ -7,7 +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. +Category rows include hibernation/VSS usage. Component-store savings are noted 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. @@ -257,6 +257,7 @@ function Invoke-SystemCleanupCategory { Category = $Name; Enabled = $enabled CandidateFiles = $(if ($native -or $blocked) { $null } else { 0 }) CandidateBytes = $(if ($native -or $blocked) { $null } else { [long]0 }) + UsageBytes = $null; UsageNote = '' RemovedFiles = 0; RemovedBytes = [long]0; FailedFiles = 0 Status = $(if ($Context.Options.ReportOnly) { 'Preview' } else { 'Completed' }) EstimateStatus = $(if ($native) { 'Not estimated' } else { 'Estimated' }) @@ -333,7 +334,7 @@ function Get-SystemCleanupShadowStorageDiagnostic { $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" } + if (-not $storage.Count) { return [pscustomobject]@{UsedBytes=[decimal]0; AllocatedBytes=[decimal]0; StoredOn=''} } $used = [decimal]0; $allocated = [decimal]0; $locations = @() foreach ($item in $storage) { # A missing measurement must not be converted to zero. @@ -346,31 +347,41 @@ function Get-SystemCleanupShadowStorageDiagnostic { $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 ', ')) + return [pscustomobject]@{UsedBytes=$used; AllocatedBytes=$allocated; StoredOn=(($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 { + if (-not $Context.OS.IsServer) { + # Store usage separately from candidate savings so totals do not overpromise. + $hibernation = $Context.Stats['DisableHibernation'] + $hibernation.UsageBytes = $null + $hibernation.UsageNote = 'file size; excluded from totals' 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) + $hibernation.UsageBytes = [long]$file.Length } catch [System.Management.Automation.ItemNotFoundException] { - $diagnostics.Hibernation = 'hiberfil.sys not present' + $hibernation.UsageBytes = [long]0 } catch { Write-SystemCleanupMessage "Hibernation diagnostic: $($_.Exception.Message)" -Detail - $diagnostics.Hibernation = 'unavailable (file inspection failed; see verbose)' + $hibernation.UsageNote = 'unavailable (file inspection failed; see verbose)' } - try { $diagnostics.ShadowStorage = Get-SystemCleanupShadowStorageDiagnostic } catch { + $shadows = $Context.Stats['ShadowCopies'] + $shadows.UsageBytes = $null + $shadows.UsageNote = 'VSS used; excluded from totals' + try { + $storage = Get-SystemCleanupShadowStorageDiagnostic + $shadows.UsageBytes = $storage.UsedBytes + if ($storage.UsedBytes -gt 0) { $shadows.UsageNote += '; newest retained' } + if ($storage.StoredOn) { $shadows.UsageNote += '; stored on ' + $storage.StoredOn } + Write-SystemCleanupMessage ('Shadow storage for {0}: {1:N2} MiB used / {2:N2} MiB allocated; stored on {3}' -f $env:SystemDrive, ($storage.UsedBytes / 1MB), ($storage.AllocatedBytes / 1MB), $storage.StoredOn) -Detail + } catch { Write-SystemCleanupMessage "Shadow-storage diagnostic: $($_.Exception.Message)" -Detail - $diagnostics.ShadowStorage = 'unavailable (storage inspection failed; see verbose)' + $shadows.UsageNote = 'unavailable (storage inspection failed; see verbose)' } } # Avoid slow DISM analysis during previews; potential savings are not measured. @@ -384,7 +395,7 @@ function Write-SystemCleanupReport { $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' + Write-SystemCleanupMessage 'DIAGNOSTICS - potential, excluded from savings totals' foreach ($entry in $Context.Diagnostics.GetEnumerator()) { Write-SystemCleanupMessage (" {0}: {1}" -f $entry.Key, $entry.Value) } @@ -404,13 +415,17 @@ function Write-SystemCleanupReport { Write-SystemCleanupMessage $heading if (-not $rows.Count) { Write-SystemCleanupMessage ' None.' } foreach ($row in $rows) { - $files = '-'; $size = '-'; $notes = @() - if ($row.EstimateStatus -eq 'Not estimated') { $notes += 'not estimated' } + $files = '-'; $size = '-'; $notes = @(); $bytes = $null + if ($row.UsageNote) { + $bytes = $row.UsageBytes + $notes += $row.UsageNote + } elseif ($row.EstimateStatus -eq 'Not estimated') { $notes += 'not estimated' } elseif ($row.EstimateStatus -eq 'Not assessed') { $notes += 'not assessed' } elseif ($null -ne $row.CandidateBytes) { $files = '{0:N0}' -f $row.CandidateFiles - $size = if ($row.CandidateBytes -gt 0 -and $row.CandidateBytes -lt (0.01 * 1MB)) { '<0.01' } else { '{0:N2}' -f ($row.CandidateBytes / 1MB) } + $bytes = $row.CandidateBytes } else { $notes += 'unavailable' } + if ($null -ne $bytes) { $size = if ($bytes -gt 0 -and $bytes -lt (0.01 * 1MB)) { '<0.01' } else { '{0:N2}' -f ($bytes / 1MB) } } if ($row.Status -notin @('Preview', 'Blocked on server')) { $notes += $row.Status } if ($row.EstimateStatus -eq 'Incomplete') { $notes += 'incomplete' } if ($row.FailedFiles) { $notes += "$($row.FailedFiles) files skipped" } diff --git a/docs/SystemCleanup.md b/docs/SystemCleanup.md index 063fc23..151c66d 100644 --- a/docs/SystemCleanup.md +++ b/docs/SystemCleanup.md @@ -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, -followed by three diagnostic lines, then every category once in three sections: +followed by a component-store note, 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 @@ -48,8 +48,8 @@ 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 show `-` and **not estimated**, not +operations such as Disk Cleanup, Search compaction, Delivery Optimization, +and component cleanup show `-` and **not estimated**, not zero. Disk Cleanup shows its preset (or Custom) and selected handler count. `None` places Disk Cleanup in the Disabled section. Servers always place it in the Blocked section, regardless of the preset. @@ -60,17 +60,23 @@ 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. +- **DisableHibernation:** the category's MiB column shows the current system-drive + `hiberfil.sys` size, or `0.00` when absent. Its note identifies this as file size. +- **ShadowCopies:** the category's MiB column shows used shadow storage for the + system volume, or `0.00` when no storage association exists. Its note identifies + VSS usage and the drive where the data resides. Storage on another drive is + labeled accordingly; it does not represent space occupied on C:. Allocation + details remain available in verbose output. - **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`. +There are no separate Hibernation or ShadowStorage diagnostic lines. The two +native rows keep `-` in the Files column. Failed/unsupported inspections show `-` +for MiB and **unavailable**, never zero. Structured results expose these usage +measurements as `UsageBytes`, separately from `CandidateBytes`. + 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 @@ -260,8 +266,9 @@ Output tests cover the duplicate-object regression, a 22-category preview under 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. +Hibernation/VSS tests cover usage in category MiB columns, zero for absence, +unknown sizes after access failures, cross-drive storage, server exclusions, no +duplicate diagnostic lines, 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), diff --git a/rmm/Start-SystemCleanup.ps1 b/rmm/Start-SystemCleanup.ps1 index 85c2098..365dcc8 100644 --- a/rmm/Start-SystemCleanup.ps1 +++ b/rmm/Start-SystemCleanup.ps1 @@ -40,7 +40,8 @@ # 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. +# Hibernation/VSS usage appears in the category MiB column (0.00 if absent). +# Report-only also notes potential component-store savings without estimating them. # 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. diff --git a/tests/Start-SystemCleanup.Tests.ps1 b/tests/Start-SystemCleanup.Tests.ps1 index 010bd27..2dfcd55 100644 --- a/tests/Start-SystemCleanup.Tests.ps1 +++ b/tests/Start-SystemCleanup.Tests.ps1 @@ -285,31 +285,45 @@ try { 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.' + Assert-Cleanup ($c.Stats.DisableHibernation.UsageBytes -eq 4GB -and $c.Stats.ShadowCopies.UsageBytes -eq 2GB -and $c.Diagnostics.ComponentStore -match 'not analyzed;.*superseded updates.*substantial.*little/none') 'Disabled options must still receive usage measurements and an honest note about potential component-store savings.' + Assert-Cleanup ($c.Stats.ShadowCopies.UsageNote.EndsWith("stored on $env:SystemDrive") -and ($script:details -join "`n") -match '3,072.00 MiB allocated') 'VSS must select the system volume, label its storage location and leave allocation details in verbose output.' $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.' + Assert-Cleanup ($report -notmatch '\bHibernation:|ShadowStorage:' -and [regex]::Matches($report,'(?m)^ ComponentStore:').Count -eq 1) 'Hibernation and VSS must not produce separate diagnostic lines.' + Assert-Cleanup ($report -match 'DisableHibernation\s+-\s+4,096.00\s+file size; excluded from totals' -and $report -match 'ShadowCopies\s+-\s+2,048.00\s+VSS used; excluded from totals; newest retained') 'Measured usage must appear in the category MiB column with its meaning and exclusion from totals.' + Assert-Cleanup ($report -notmatch '(DisableHibernation|ShadowCopies).*not estimated|GiB|MiB allocated') 'Measured rows must not say not estimated or repeat allocation diagnostics.' $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.' + $null=Get-SystemCleanupDiagnostics $c + Assert-Cleanup ($c.Stats.ShadowCopies.UsageBytes -eq 2GB -and $c.Stats.ShadowCopies.UsageNote -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.' + Assert-Cleanup ($c.Stats.DisableHibernation.UsageBytes -eq 0 -and $c.Stats.ShadowCopies.UsageBytes -eq 0) 'Absent hibernation or a missing shadow-storage association must measure zero bytes.' + $script:messages=@(); Write-SystemCleanupReport $c + $report=$script:messages -join "`n" + Assert-Cleanup ($report -match 'DisableHibernation\s+-\s+0.00\s' -and $report -match 'ShadowCopies\s+-\s+0.00\s' -and $report -notmatch 'hiberfil.sys not present|no shadow-storage association|\bHibernation:|ShadowStorage:') 'Absent usage must appear as zero MiB in the two rows without separate absence messages.' $script:storageState='invalid' - Assert-Cleanup ((Get-SystemCleanupDiagnostics $c).ShadowStorage -match 'unavailable') 'Missing VSS measurements must not become zero.' + $null=Get-SystemCleanupDiagnostics $c + Assert-Cleanup ($null -eq $c.Stats.ShadowCopies.UsageBytes -and $c.Stats.ShadowCopies.UsageNote -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.' + Assert-Cleanup ($null -eq $c.Stats.DisableHibernation.UsageBytes -and $null -eq $c.Stats.ShadowCopies.UsageBytes -and $c.Stats.DisableHibernation.UsageNote -match 'unavailable' -and $c.Stats.ShadowCopies.UsageNote -match 'unavailable' -and $d.ComponentStore -match 'not analyzed' -and $c.Errors -eq 0) 'Diagnostic failures must clear old measurements, preserve the component note and not fail reporting.' + $script:messages=@(); Write-SystemCleanupReport $c + $report=$script:messages -join "`n" + Assert-Cleanup ($report -match 'DisableHibernation\s+-\s+-\s+unavailable' -and $report -match 'ShadowCopies\s+-\s+-\s+unavailable') 'Failed inspections must display unknown size rather than zero MiB.' $script:fileReads=0; $script:storageReads=0 - $c.OS.IsServer=$true + $c=New-CleanupContext -Server $true + foreach ($name in @('DisableHibernation','ShadowCopies')) { Invoke-SystemCleanupCategory $c $name {} } $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.' + Assert-Cleanup ($script:fileReads -eq 0 -and $script:storageReads -eq 0 -and $script:diagnosticProcesses -eq 0 -and $null -eq $c.Stats.DisableHibernation.UsageBytes -and $null -eq $c.Stats.ShadowCopies.UsageBytes -and $d.Count -eq 1 -and $d.ComponentStore -match 'not analyzed') 'Server reports must block hibernation/VSS assessment and only note potential component-store savings.' + $script:messages=@(); Write-SystemCleanupReport $c + $report=$script:messages -join "`n" + Assert-Cleanup ($report -match 'DisableHibernation\s+-\s+-\s+not assessed' -and $report -match 'ShadowCopies\s+-\s+-\s+not assessed') 'Server-blocked rows must remain unassessed rather than showing zero usage.' $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.' @@ -536,10 +550,10 @@ try { 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_Volume { [pscustomobject]@{DriveLetter=$env:SystemDrive; DeviceID='\\?\Volume{11111111-1111-1111-1111-111111111111}\'} } 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}'} + [pscustomobject]@{VolumeName='\\?\Volume{11111111-1111-1111-1111-111111111111}\'; InstallDate=[datetime]'2026-10-01'; ID='{11111111-1111-1111-1111-111111111111}'} + [pscustomobject]@{VolumeName='\\?\Volume{11111111-1111-1111-1111-111111111111}\'; InstallDate=[datetime]'2026-10-02'; ID='{22222222-2222-2222-2222-222222222222}'} } } } @@ -567,7 +581,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.' + Assert-Cleanup ($compactOutput -match 'DisableHibernation\s+-\s+<0.01\s+file size' -and $compactOutput -match 'ShadowCopies\s+-\s+0.00\s+VSS used' -and $compactOutput -notmatch '\bHibernation:|ShadowStorage:' -and $compactOutput -match 'ComponentStore: not analyzed;.*superseded updates.*substantial.*little/none') 'Full entry-point report must show usage in category rows and retain the component note even with cleanup disabled.' function Test-SystemCleanupAppRunning { return $true } function Get-Command { return $null } $o.DiskCleanupItems=@(); $o.DiskCleanupPreset='None'