2026-10-22 16:58:12 -04:00
# 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'
2026-10-23 11:22:55 -04:00
Assert-Cleanup ( $core . Extent . Text -notmatch '(?i)AnalyzeComponentStore|dism\.exe' ) 'Reports must not ship a DISM analysis invocation.'
2026-10-22 16:58:12 -04:00
foreach ( $definition in $core . FindAll ({ param ( $n ) $n -is [ Management.Automation.Language.FunctionDefinitionAst ]}, $false )) {
. ([ scriptblock ]:: Create ( $definition . Extent . Text ))
}
2026-10-23 12:25:00 -04:00
# Never contend with a real deployment on the test host.
function New-SystemCleanupOfficeMutex { return [ Threading.Mutex ]:: new ( $false ) }
2026-10-22 17:10:16 -04:00
$messageWriter = ${ function : Write-SystemCleanupMessage }
$script:messages = @ (); $script:details = @ ()
function Write-SystemCleanupMessage {
param ( $Message , [ switch ] $Detail )
if ( $Detail ) { $script:details += $Message } else { $script:messages += $Message }
}
& {
$VerbosePreference = 'SilentlyContinue'
$visible = @ (& $messageWriter 'compact output' 6 >& 1 )
$hidden = @ (& $messageWriter 'handler inventory' -Detail 4 >& 1 6 >& 1 )
Assert-Cleanup ( $visible . Count -eq 1 -and [ string ] $visible [ 0 ] -match 'compact output' -and $hidden . Count -eq 0 ) 'Verbose diagnostics must not consume the normal RMM output budget.'
$VerbosePreference = 'Continue'
$verbose = @ (& $messageWriter 'handler inventory' -Detail 4 >& 1 )
Assert-Cleanup ( $verbose . Count -eq 1 -and $verbose [ 0 ] -is [ Management.Automation.VerboseRecord ]) 'Full diagnostics must remain available on the verbose stream.'
}
& {
# Run the actual entry statement with an inert function. The host summary
# must survive, while success-stream objects must not become a second report.
function Invoke-SystemCleanup {
param ( $Options )
Write-SystemCleanupMessage 'entry summary'
[ pscustomobject ] @ { Category = 'Fixture' ; Enabled = $true ; CandidateFiles = 1 }
}
$script:messages = @ ()
$output = @ (& ([ scriptblock ]:: Create ( $core . EndBlock . Statements [ -1 ]. Extent . Text )))
Assert-Cleanup ( $output . Count -eq 0 -and $script:messages -contains 'entry summary' ) 'Core entry must suppress the duplicate object dump without suppressing the summary.'
}
2026-10-22 16:58:12 -04:00
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 )
2026-10-23 12:25:00 -04:00
Assert-Cleanup ( $result . Count -eq 23 -and @ ( $result | Where-Object Status -eq 'Blocked on server' ). Count -eq $blocked . Count ) 'Server report must list every blocked category.'
2026-10-22 16:58:12 -04:00
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.' }
2026-10-22 17:10:16 -04:00
$script:messages = @ (); $script:details = @ ()
2026-10-22 16:58:12 -04:00
Invoke-SystemCleanupCategory $c 'DiskCleanup' { Invoke-SystemCleanupDiskCleanup $c }
Write-SystemCleanupReport $c
$report = $script:messages -join " `n "
2026-10-22 17:10:16 -04:00
Assert-Cleanup ( $report -match '(?s)DISABLED -.*DiskCleanup\s+-\s+-\s+.*None \(0 handlers\); will not run' ) 'None must appear in the disabled report section with a clear explanation.'
Assert-Cleanup (( $script:details -join " `n " ) -match 'items not selected.*Previous Installations' -and $report -notmatch 'Previous Installations|CleanupDiskCleanup=' ) 'Unselected handler inventories belong in verbose diagnostics, not the compact report.'
2026-10-22 16:58:12 -04:00
$c . Options . ReportOnly = $false
Invoke-SystemCleanupDiskCleanup $c
Assert-Cleanup ( $c . Errors -eq 0 ) 'None must not attempt native cleanup, even through the helper directly.'
}
2026-10-23 11:22:55 -04:00
# 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 = 4 GB; 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 { 2 GB }); AllocatedSpace = 3 GB}
[ pscustomobject ] @ { Volume =[ pscustomobject ] @ { DeviceID = $otherId }; DiffVolume =[ pscustomobject ] @ { DeviceID = $otherId }; UsedSpace = 99 GB; AllocatedSpace = 100 GB}
}
}
$c = New-CleanupContext
foreach ( $name in @ ( 'DisableHibernation' , 'ShadowCopies' , 'ComponentStore' )) {
$c . Options [ $name ]= $false
Invoke-SystemCleanupCategory $c $name {}
}
$c . Diagnostics = Get-SystemCleanupDiagnostics $c
2026-10-23 11:33:03 -04:00
Assert-Cleanup ( $c . Stats . DisableHibernation . UsageBytes -eq 4 GB -and $c . Stats . ShadowCopies . UsageBytes -eq 2 GB -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.'
2026-10-23 11:22:55 -04:00
$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 "
2026-10-23 11:33:03 -04:00
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.'
2026-10-23 11:22:55 -04:00
$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
2026-10-23 11:33:03 -04:00
$null = Get-SystemCleanupDiagnostics $c
Assert-Cleanup ( $c . Stats . ShadowCopies . UsageBytes -eq 2 GB -and $c . Stats . ShadowCopies . UsageNote -match 'stored on Z:' ) 'Shadow storage on another drive must not be attributed to the system drive.'
2026-10-23 11:22:55 -04:00
$script:storageState = 'empty' ; $script:hiberState = 'missing'
$d = Get-SystemCleanupDiagnostics $c
2026-10-23 11:33:03 -04:00
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.'
2026-10-23 11:22:55 -04:00
$script:storageState = 'invalid'
2026-10-23 11:33:03 -04:00
$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.'
2026-10-23 11:22:55 -04:00
$script:storageState = 'denied' ; $script:hiberState = 'denied'
$d = Get-SystemCleanupDiagnostics $c
2026-10-23 11:33:03 -04:00
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.'
2026-10-23 11:22:55 -04:00
$script:fileReads = 0 ; $script:storageReads = 0
2026-10-23 11:33:03 -04:00
$c = New-CleanupContext -Server $true
foreach ( $name in @ ( 'DisableHibernation' , 'ShadowCopies' )) { Invoke-SystemCleanupCategory $c $name {} }
2026-10-23 11:22:55 -04:00
$d = Get-SystemCleanupDiagnostics $c
2026-10-23 11:33:03 -04:00
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.'
2026-10-23 11:22:55 -04:00
$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.'
}
2026-10-23 12:25:00 -04:00
# Abandoned Office payloads: report/apply, disabled options, server support,
# identity, retention, process/lock/link protection, and durable helper survival.
& {
$officeAst = Read-CleanupAst 'Install-MicrosoftOffice365.ps1'
foreach ( $definition in $officeAst . FindAll ({ param ( $n ) $n -is [ Management.Automation.Language.FunctionDefinitionAst ] -and $n . Name -in @ ( 'Get-OfficeDeploymentDefinitions' , 'Get-OfficeStagingNames' )}, $false )) {
. ([ scriptblock ]:: Create ( $definition . Extent . Text ))
}
$names = @ ( Get-OfficeStagingNames )
$script:officeProcesses = @ (); $script:officeInventoryFails = $false
function Get-CimInstance { if ( $script:officeInventoryFails ) { throw 'Synthetic process inventory failure' }; $script:officeProcesses }
function New-StageFixture {
param ( $Parent , $Id )
$relative = $Parent + '\' +( $Id * 32 )
$null = New-CleanupFixture ( $relative + '\options.json' ) '{"ProductId":"O365BusinessRetail","OfficeArchitecture":"64","UpdateChannel":"Current"}'
foreach ( $name in $names ) {
$leaf = if ( $name -in @ ( 'ODT' , 'GetHelp' )) { $name + '\payload.dat' } else { $name }
$null = New-CleanupFixture ( $relative + '\' + $leaf )
}
foreach ( $name in @ ( 'Office-UserCleanup.ps1' , 'user-cleanup.lock' , 'install.xml' , 'office-install.stdout.log' , 'unknown.exe' )) { $null = New-CleanupFixture ( $relative + '\' + $name ) }
$folder = Join-Path $testRoot $relative
foreach ( $dir in @ ( Get-ChildItem -LiteralPath $folder -Recurse -Directory )+ @ ( Get-Item -LiteralPath $folder )) { [ IO.Directory ]:: SetLastWriteTimeUtc ( $dir . FullName ,[ datetime ]:: UtcNow . AddDays ( -60 )) }
return $folder
}
function Test-StageCleanup {
param ([ bool ] $ReportOnly = $true ,[ bool ] $Enabled = $true ,[ bool ] $Server = $false )
$c = New-CleanupContext -ReportOnly $ReportOnly -Server $Server ; $c . Options . OfficeStaging = $Enabled
Invoke-SystemCleanupCategory $c 'OfficeStaging' { Clear-SystemCleanupOfficeStaging $c $stageRoots ([ datetime ]:: UtcNow . AddDays ( -7 )) }
return $c
}
$folder = New-StageFixture 'office-fixture\Windows\SystemTemp\EmberkomOfficeDeployment' 'a'
$legacy = New-StageFixture 'office-fixture\ProgramData\EmberkomOfficeDeployment' 'b'
$stageRoots = @ (( Split-Path -Parent $folder ),( Split-Path -Parent $legacy ))
Assert-Cleanup (( Get-SystemCleanupOfficeStagingRoots @ ()) -contains ( Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment' )) 'SystemTemp must be a supported Office staging root.'
$c = Test-StageCleanup -Enabled $false
Assert-Cleanup ( $c . Stats . OfficeStaging . CandidateFiles -eq ( 2 * $names . Count ) -and ! $c . Stats . OfficeStaging . Enabled -and ( Test-Path -LiteralPath ( Join-Path $folder 'ODT\payload.dat' ))) 'Disabled report must measure every installer artifact without deleting it.'
$c = Test-StageCleanup -Server $true
Assert-Cleanup ( $c . Stats . OfficeStaging . CandidateFiles -eq ( 2 * $names . Count ) -and $c . Errors -eq 0 ) 'Owned staging cleanup must support server OSes.'
$c = New-CleanupContext
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' ( Split-Path -Parent $stageRoots [ 0 ]) ([ datetime ]:: UtcNow . AddDays ( -7 )) -Recurse }
Assert-Cleanup ( $c . Stats . SystemTemp . CandidateFiles -eq 0 ) 'Generic temp traversal must exclude Office staging entirely.'
$c = Test-StageCleanup -ReportOnly $false -Enabled $false
Assert-Cleanup (( Test-Path -LiteralPath ( Join-Path $folder 'ODT\payload.dat' )) -and ! $c . Stats . Count ) 'Disabled apply must preserve staged media.'
$script:officeProcesses = @ ([ pscustomobject ] @ { Name = 'setup.exe' })
$c = Test-StageCleanup
Assert-Cleanup ( $c . Stats . OfficeStaging . Status -eq 'Skipped' -and $c . Stats . OfficeStaging . EstimateStatus -eq 'Not assessed' ) 'An installer without a workspace path must block staging cleanup.'
$script:officeProcesses = @ ([ pscustomobject ] @ { Name = 'worker.exe' ; ExecutablePath =( Join-Path $folder 'ODT\worker.exe' )})
$c = Test-StageCleanup
Assert-Cleanup ( $c . Stats . OfficeStaging . CandidateFiles -eq $names . Count -and $c . Stats . OfficeStaging . Notes -match 'retained' ) 'A running process must retain its workspace while allowing other abandoned media.'
$script:officeProcesses = @ (); $script:officeInventoryFails = $true
$c = Test-StageCleanup -ReportOnly $false
Assert-Cleanup ( $c . Errors -eq 1 -and ( Test-Path -LiteralPath ( Join-Path $folder 'ODT\payload.dat' ))) 'Failed process inventory must prevent deletion.'
$script:officeInventoryFails = $false
& {
function New-SystemCleanupOfficeMutex {
$m =[ pscustomobject ] @ {}
$m | Add-Member ScriptMethod WaitOne { param ( $Timeout ) return $false }
$m | Add-Member ScriptMethod Dispose { }
return $m
}
$c = Test-StageCleanup -ReportOnly $false
Assert-Cleanup ( $c . Stats . OfficeStaging . Status -eq 'Skipped' -and ( Test-Path -LiteralPath ( Join-Path $folder 'odt.exe' ))) 'Active deployment mutex must block cleanup.'
}
$payload = Join-Path $folder 'ODT\payload.dat'
$handle =[ IO.File ]:: Open ( $payload ,[ IO.FileMode ]:: Open ,[ IO.FileAccess ]:: Read ,[ IO.FileShare ]:: None )
try { $c = Test-StageCleanup ; Assert-Cleanup ( $c . Stats . OfficeStaging . CandidateFiles -eq $names . Count ) 'Locked media must not count as reclaimable.' } finally { $handle . Dispose () }
[ IO.File ]:: SetLastWriteTimeUtc ( $payload ,[ datetime ]:: UtcNow )
$c = Test-StageCleanup
Assert-Cleanup ( $c . Stats . OfficeStaging . CandidateFiles -eq $names . Count ) 'A fresh payload must retain the whole workspace media set.'
[ IO.File ]:: SetLastWriteTimeUtc ( $payload ,[ datetime ]:: UtcNow . AddDays ( -60 ))
$outside = New-CleanupFixture 'office-outside\keep.dat'
$junction = Join-Path $folder 'ODT\linked'
$null = New-Item -ItemType Junction -Path $junction -Target ( Split-Path -Parent $outside )
try {
[ IO.Directory ]:: SetLastWriteTimeUtc (( Split-Path -Parent $junction ),[ datetime ]:: UtcNow . AddDays ( -60 ))
$c = Test-StageCleanup
Assert-Cleanup ( $c . Stats . OfficeStaging . CandidateFiles -eq $names . Count -and ( Test-Path -LiteralPath $outside )) 'Linked artifacts must retain the whole media set without traversing the link.'
} finally { [ IO.Directory ]:: Delete ( $junction , $false ); [ IO.Directory ]:: SetLastWriteTimeUtc (( Split-Path -Parent $junction ),[ datetime ]:: UtcNow . AddDays ( -60 )) }
$marker = Join-Path $folder 'options.json' ; [ IO.File ]:: WriteAllText ( $marker , '{}' ); [ IO.File ]:: SetLastWriteTimeUtc ( $marker ,[ datetime ]:: UtcNow . AddDays ( -60 ))
$c = Test-StageCleanup
Assert-Cleanup ( $c . Stats . OfficeStaging . CandidateFiles -eq $names . Count ) 'Unrecognized folders must not be deleted based only on their names.'
[ IO.File ]:: WriteAllText ( $marker , '{"ProductId":"O365BusinessRetail","OfficeArchitecture":"64","UpdateChannel":"Current"}' ); [ IO.File ]:: SetLastWriteTimeUtc ( $marker ,[ datetime ]:: UtcNow . AddDays ( -60 ))
$c = Test-StageCleanup -ReportOnly $false
Assert-Cleanup ( $c . Errors -eq 0 -and $c . Stats . OfficeStaging . RemovedFiles -eq ( 2 * $names . Count ) -and !( Test-Path -LiteralPath ( Join-Path $folder 'ODT' )) -and !( Test-Path -LiteralPath ( Join-Path $legacy 'ODT' ))) 'Apply must remove known aged media from SystemTemp and legacy ProgramData.'
foreach ( $workspace in @ ( $folder , $legacy )) {
foreach ( $name in @ ( 'options.json' , 'Office-UserCleanup.ps1' , 'user-cleanup.lock' , 'install.xml' , 'office-install.stdout.log' , 'unknown.exe' )) {
Assert-Cleanup ( Test-Path -LiteralPath ( Join-Path $workspace $name )) "Office staging cleanup removed protected data: $name "
}
}
}
2026-10-22 16:58:12 -04:00
# 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 "
2026-10-22 17:10:16 -04:00
Assert-Cleanup ( $report . IndexOf ( 'ENABLED -' ) -lt $report . IndexOf ( 'DISABLED -' ) -and $report . IndexOf ( 'DuplicateDownloads' ) -lt $report . IndexOf ( 'DISABLED -' ) -and $report . IndexOf ( 'DownloadedExecutables' ) -gt $report . IndexOf ( 'DISABLED -' )) 'Enabled and disabled report groups are unclear or misplaced.'
Assert-Cleanup ( $report . IndexOf ( 'Known savings:' ) -lt $report . IndexOf ( 'ENABLED -' ) -and $report -match 'Additional DISABLED' -and $report -match '<0.01' ) 'Unique totals must appear first and small nonzero candidates must remain visible.'
2026-10-22 16:58:12 -04:00
$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' )} }
2026-10-23 11:33:03 -04:00
Win32_Volume { [ pscustomobject ] @ { DriveLetter = $env:SystemDrive ; DeviceID = '\\?\Volume{11111111-1111-1111-1111-111111111111}\' } }
2026-10-22 16:58:12 -04:00
Win32_ShadowCopy {
2026-10-23 11:33:03 -04:00
[ 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}' }
2026-10-22 16:58:12 -04:00
}
}
}
function Test-SystemCleanupAppRunning { return $false }
2026-10-23 12:25:00 -04:00
function Get-SystemCleanupOfficeStagingRoots { return ( Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment' ) }
2026-10-22 16:58:12 -04:00
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
2026-10-22 17:10:16 -04:00
$script:messages = @ (); $script:details = @ ()
2026-10-22 16:58:12 -04:00
$result = @ ( Invoke-SystemCleanup $o )
2026-10-23 12:25:00 -04:00
Assert-Cleanup ( $result . Count -eq 23 -and @ ( $result | Where-Object Status -ne 'Preview' ). Count -eq 0 ) "Full preview did not cover every category (count= $( $result . Count ) )."
2026-10-22 16:58:12 -04:00
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.'
2026-10-22 17:10:16 -04:00
$compactOutput = ( $script:messages | ForEach-Object { '[SystemCleanup] ' + $_ }) -join " `r`n "
$script:compactReportBytes = [ Text.Encoding ]:: UTF8 . GetByteCount ( $compactOutput )
2026-10-23 12:25:00 -04:00
Assert-Cleanup ( $script:compactReportBytes -lt 4096 ) "23-category preview exceeded the 4 KiB regression budget ( $script:compactReportBytes bytes)."
2026-10-22 17:10:16 -04:00
foreach ( $row in $result ) {
Assert-Cleanup ([ regex ]:: Matches ( $compactOutput , ( '(?m)^\[SystemCleanup\] ' + [ regex ]:: Escape ( $row . Category ) + '\s' )). Count -eq 1 ) "Compact report lost or repeated category $( $row . Category ) ."
}
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.'
2026-10-23 11:33:03 -04:00
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.'
2026-10-22 16:58:12 -04:00
function Test-SystemCleanupAppRunning { return $true }
function Get-Command { return $null }
$o . DiskCleanupItems = @ (); $o . DiskCleanupPreset = 'None'
2026-10-22 17:10:16 -04:00
$script:messages = @ ()
2026-10-22 16:58:12 -04:00
$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.'
2026-10-22 17:10:16 -04:00
$compactOutput = $script:messages -join " `n "
Assert-Cleanup ( $compactOutput -match 'BrowserCache.*Partial; incomplete.*chrome.*msedge' -and $compactOutput -match 'RevitJournals.*Skipped.*Revit is running' -and $compactOutput -match 'DeliveryOptimization.*Unavailable.*not installed' ) 'Compacting output must preserve partial, skipped and unavailable reasons.'
2026-10-22 16:58:12 -04:00
} finally {
$env:SystemRoot = $savedEnvironment . SystemRoot ; $env:SystemDrive = $savedEnvironment . SystemDrive ; $env:ProgramData = $savedEnvironment . ProgramData
}
}
2026-10-22 17:10:16 -04:00
& {
$c = New-CleanupContext
$script:messages = @ (); $script:details = @ ()
Invoke-SystemCleanupCategory $c 'CrashDumps' { throw ( "Synthetic failure `r`n " + ( 'long diagnostic ' * 300 )) }
Write-SystemCleanupReport $c
$report = $script:messages -join " `n "
Assert-Cleanup ( $c . Errors -eq 1 -and $report -match 'CrashDumps.*Failed; incomplete.*Synthetic failure.*see verbose' -and $report . Length -lt 1600 ) 'A long multiline error must retain its failure status without flooding the summary.'
Assert-Cleanup (( $script:details -join " `n " ). Contains (( 'long diagnostic ' * 300 ))) 'Compacted errors must remain complete in verbose diagnostics.'
}
2026-10-23 12:25:00 -04:00
Write-Host "Compact 23-category preview: $script:compactReportBytes UTF-8 bytes."
2026-10-22 16:58:12 -04:00
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 }
}