488 lines
36 KiB
PowerShell
488 lines
36 KiB
PowerShell
#Requires -Version 5.1
|
|
# Offline: AST-load cleanup functions; mock shim downloads and native operations.
|
|
$ErrorActionPreference = 'Stop'
|
|
$repo = Split-Path -Parent $PSScriptRoot
|
|
$testRoot = Join-Path $env:TEMP ('SystemCleanupTests-' + [guid]::NewGuid().ToString('N'))
|
|
$null = New-Item -ItemType Directory -Path $testRoot
|
|
$script:assertions = 0
|
|
function Assert-Cleanup { param([bool]$Condition, [string]$Message) $script:assertions++; if (-not $Condition) { throw $Message } }
|
|
function Assert-CleanupThrows {
|
|
param([scriptblock]$Action, [string]$Pattern)
|
|
$caught = $null
|
|
try { & $Action | Out-Null } catch { $caught = $_ }
|
|
Assert-Cleanup ($null -ne $caught -and $caught.Exception.Message -match $Pattern) "Expected '$Pattern', got '$caught'."
|
|
}
|
|
function Read-CleanupAst {
|
|
param([string]$File)
|
|
$tokens = $null; $errors = $null
|
|
$ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $repo $File), [ref]$tokens, [ref]$errors)
|
|
if ($errors.Count) { throw ($errors | Out-String) }
|
|
return $ast
|
|
}
|
|
function New-CleanupFixture {
|
|
param([string]$Relative, [string]$Content = 'fixture', [int]$Days = 60)
|
|
$path = Join-Path $testRoot $Relative
|
|
$null = [IO.Directory]::CreateDirectory((Split-Path -Parent $path))
|
|
[IO.File]::WriteAllText($path, $Content)
|
|
[IO.File]::SetLastWriteTimeUtc($path, [datetime]::UtcNow.AddDays(-$Days))
|
|
return $path
|
|
}
|
|
try {
|
|
$core = Read-CleanupAst 'Start-SystemCleanup.ps1'
|
|
$shim = Read-CleanupAst 'rmm/Start-SystemCleanup.ps1'
|
|
foreach ($definition in $core.FindAll({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst]}, $false)) {
|
|
. ([scriptblock]::Create($definition.Extent.Text))
|
|
}
|
|
$script:messages = @()
|
|
function Write-SystemCleanupMessage { param($Message) $script:messages += $Message }
|
|
function New-CleanupContext {
|
|
param([bool]$ReportOnly = $true, [bool]$Server = $false)
|
|
return @{
|
|
Options = Get-SystemCleanupOptions; OS = [pscustomobject]@{IsServer=$Server; Caption='Fixture'}
|
|
Stats=[ordered]@{}; Errors=0
|
|
Seen=New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
|
|
} | ForEach-Object { $_.Options.ReportOnly=$ReportOnly; $_ }
|
|
}
|
|
# Defaults and RMM shared scope: values defined outside the loader must survive.
|
|
$options = Get-SystemCleanupOptions
|
|
Assert-Cleanup ($options.ReportOnly -and $options.TempDays -eq 7 -and $options.DiagnosticDays -eq 30) 'Unsafe defaults.'
|
|
Assert-Cleanup ($options.DiskCleanupPreset -eq 'Standard' -and -not $options.ContainsKey('DiskCleanup')) 'Disk Cleanup must use a single selection, defaulting to Standard.'
|
|
# Lock down the intended policy: adding handlers changes what operators permit.
|
|
$expectedStandard = @('Downloaded Program Files','Internet Cache Files','Thumbnail Cache','Active Setup Temp Folders','Temporary Setup Files','Windows Defender','RetailDemo Offline Content')
|
|
$expectedUpdates = @('Service Pack Cleanup','Update Cleanup','Upgrade Discarded Files','Windows Upgrade Log Files')
|
|
$expectedDiagnostics = @('Memory Dump Files','Old ChkDsk Files','System error memory dump files','System error minidump files','Setup Log Files','Windows Error Reporting Archive Files','Windows Error Reporting Queue Files','Windows Error Reporting System Archive Files','Windows Error Reporting System Queue Files','Windows Error Reporting Temp Files')
|
|
$expectedPresets = [ordered]@{
|
|
Standard = $expectedStandard
|
|
StandardAndUpdates = @($expectedStandard + $expectedUpdates)
|
|
StandardUpdatesAndDiagnostics = @($expectedStandard + $expectedUpdates + $expectedDiagnostics)
|
|
All = @(Get-SystemCleanupHandlers)
|
|
None = @()
|
|
}
|
|
foreach ($presetName in $expectedPresets.Keys) {
|
|
& {
|
|
$CleanupDiskCleanupItems = ' ' + $presetName.ToLowerInvariant() + ' '
|
|
$parsed = Get-SystemCleanupOptions
|
|
Assert-Cleanup ($parsed.DiskCleanupPreset -ceq $presetName) "Preset normalization failed: $presetName"
|
|
Assert-Cleanup (($parsed.DiskCleanupItems -join '|') -ceq ($expectedPresets[$presetName] -join '|')) "Unexpected cleanup scope for $presetName"
|
|
Assert-Cleanup ($parsed.DiskCleanupItems -is [array]) "Preset $presetName did not produce an array."
|
|
}
|
|
}
|
|
& {
|
|
$CleanupDiskCleanupItems = @(' thumbnail cache ', 'INTERNET CACHE FILES', 'Thumbnail Cache')
|
|
$parsed = Get-SystemCleanupOptions
|
|
Assert-Cleanup ($parsed.DiskCleanupPreset -eq 'Custom' -and ($parsed.DiskCleanupItems -join ',') -ceq 'Thumbnail Cache,Internet Cache Files') 'Custom arrays must normalize and deduplicate handlers.'
|
|
foreach ($invalid in @('Standrad', 'None,Thumbnail Cache', 'Standard,All', 'Standard,Internet Cache Files')) {
|
|
$CleanupDiskCleanupItems = $invalid
|
|
Assert-CleanupThrows { Get-SystemCleanupOptions } 'Unknown Disk Cleanup preset or item'
|
|
}
|
|
foreach ($blank in @('', ' ', ',', $null, @())) {
|
|
$CleanupDiskCleanupItems = $blank
|
|
Assert-CleanupThrows { Get-SystemCleanupOptions } 'cannot be blank'
|
|
}
|
|
}
|
|
& {
|
|
foreach ($oldValue in @('false', 'true')) {
|
|
$CleanupDiskCleanup = $oldValue
|
|
Assert-CleanupThrows { Get-SystemCleanupOptions } 'CleanupDiskCleanup has been removed'
|
|
}
|
|
}
|
|
& {
|
|
$CleanupReportOnly = 'false'; $CleanupShadowCopies = ' no '; $CleanupTempDays = '14'
|
|
$CleanupDiskCleanupItems = 'Thumbnail Cache,Internet Cache Files'
|
|
$o = Get-SystemCleanupOptions
|
|
Assert-Cleanup (-not $o.ReportOnly -and -not $o.ShadowCopies -and $o.TempDays -eq 14 -and $o.DiskCleanupItems.Count -eq 2) 'Caller scope/text parsing failed.'
|
|
Assert-Cleanup ($CleanupReportOnly -ceq 'false' -and $CleanupTempDays -ceq '14') 'Caller variables were overwritten.'
|
|
$CleanupReportOnly = 'maybe'; Assert-CleanupThrows { Get-SystemCleanupOptions } 'must be true or false'
|
|
$CleanupReportOnly = $true; $CleanupTempDays = 0; Assert-CleanupThrows { Get-SystemCleanupOptions } 'whole number'
|
|
$CleanupTempDays = 7; $CleanupDiskCleanupItems = 'Unknown handler'; Assert-CleanupThrows { Get-SystemCleanupOptions } 'Unknown Disk Cleanup'
|
|
}
|
|
$legacy = Get-Content -LiteralPath (Join-Path $repo 'Start-Cleanup.ps1') -Raw
|
|
$legacyHandlers = @([regex]::Matches($legacy, '"([^"\r\n]+)"\s*=\s*\$(?:true|false);') | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique)
|
|
foreach ($handler in $legacyHandlers) { Assert-Cleanup ($handler -in (Get-SystemCleanupHandlers)) "Lost legacy cleanup handler: $handler" }
|
|
Assert-Cleanup ($legacyHandlers.Count -eq (Get-SystemCleanupHandlers).Count) 'Unexpected handler inventory mismatch.'
|
|
$runCommand = $shim.Find({param($n) $n -is [Management.Automation.Language.CommandAst] -and $n.GetCommandName() -eq 'Run-Script'}, $true)
|
|
Assert-Cleanup ($runCommand.Extent.Text -eq 'Run-Script -LivePSScript Start-SystemCleanup') 'Shim must use dot-sourcing Run-Script without Arguments.'
|
|
& {
|
|
# Exercise the actual shim and real Run-Script with Syncro-style strings.
|
|
# Both download implementations return inert source; no real WebClient is created.
|
|
$toolsAst=Read-CleanupAst 'Tools.ps1'
|
|
$runner=$toolsAst.Find({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq 'Run-Script'}, $true)
|
|
$script:cleanupMockTools=$runner.Extent.Text
|
|
$fixtureWorkload=New-CleanupFixture 'rmm-scope.ps1' 'Get-SystemCleanupOptions'
|
|
function IsURLValid { return $true }
|
|
function Download-File { return $fixtureWorkload }
|
|
function New-Object {
|
|
param($TypeName)
|
|
if ($TypeName -ne 'Net.WebClient') { throw "Unexpected object in shim probe: $TypeName" }
|
|
$client=[pscustomobject]@{}
|
|
$client | Add-Member ScriptMethod DownloadString {
|
|
param($URL)
|
|
if ($URL -match '/Tools\.ps1$') { return $script:cleanupMockTools }
|
|
if ($URL -match '/Start-SystemCleanup\.ps1$') { return 'Get-SystemCleanupOptions' }
|
|
throw "Unexpected URL in shim probe: $URL"
|
|
}
|
|
return $client
|
|
}
|
|
[string]$CleanupReportOnly='false'
|
|
[string]$CleanupSystemTemp='false'
|
|
[string]$CleanupTempDays='14'
|
|
foreach ($selectionName in @($expectedPresets.Keys) + @('Thumbnail Cache')) {
|
|
[string]$CleanupDiskCleanupItems=$selectionName
|
|
$output=@(. ([scriptblock]::Create($shim.Extent.Text)))
|
|
$selected=@($output | Where-Object { $_ -is [hashtable] })
|
|
Assert-Cleanup ($selected.Count -eq 1) 'Shim did not return the inert workload result.'
|
|
$injectedOptions=$selected[0]
|
|
Assert-Cleanup (-not $injectedOptions.ReportOnly -and -not $injectedOptions.SystemTemp -and $injectedOptions.TempDays -eq 14) 'Run-Script lost Syncro-injected strings.'
|
|
$expectedItems = if ($selectionName -eq 'Thumbnail Cache') { @('Thumbnail Cache') } else { @($expectedPresets[$selectionName]) }
|
|
Assert-Cleanup (($injectedOptions.DiskCleanupItems -join '|') -ceq ($expectedItems -join '|')) "Run-Script lost the injected selection: $selectionName"
|
|
Assert-Cleanup ($injectedOptions.DiagnosticDays -eq 30 -and $CleanupReportOnly -ceq 'false' -and $CleanupTempDays -ceq '14' -and $CleanupDiskCleanupItems -ceq $selectionName) 'Absent defaults or original caller variables changed.'
|
|
}
|
|
}
|
|
|
|
# All server/DC gates, including when enabled, and unknown OS failure.
|
|
$blocked = @('ShadowCopies','DisableHibernation','CompactSearch','DownloadedExecutables','DuplicateDownloads','OutlookBackups','ITunesBackups','DiskCleanup')
|
|
& {
|
|
function Get-CimInstance { param($ClassName) if ($ClassName -eq 'Win32_OperatingSystem') { [pscustomobject]@{ProductType=$script:productType; Caption='Fixture OS'} } }
|
|
foreach ($script:productType in @(1,2,3)) {
|
|
$os = Get-SystemCleanupOS
|
|
Assert-Cleanup ($os.IsServer -eq ($script:productType -ne 1)) 'ProductType classification failed.'
|
|
$c = New-CleanupContext -Server $os.IsServer
|
|
foreach ($name in $blocked) {
|
|
if ($name -ne 'DiskCleanup') { $c.Options[$name]=$true }
|
|
$script:ran=$false
|
|
Invoke-SystemCleanupCategory $c $name { $script:ran=$true }
|
|
Assert-Cleanup ($script:ran -eq (-not $os.IsServer)) "Incorrect server gate for $name / $script:productType"
|
|
}
|
|
}
|
|
foreach ($script:productType in @(0,4,$null)) { Assert-CleanupThrows { Get-SystemCleanupOS } 'Cannot identify OS' }
|
|
function Get-CimInstance { throw 'Synthetic CIM failure' }
|
|
Assert-CleanupThrows { Get-SystemCleanupOS } 'Synthetic CIM failure'
|
|
}
|
|
$serverContext = New-CleanupContext -Server $true
|
|
Assert-CleanupThrows { Invoke-SystemCleanupDiskCleanup $serverContext } 'blocked on server'
|
|
Assert-CleanupThrows { Invoke-SystemCleanupShadows $serverContext } 'blocked on server'
|
|
Assert-CleanupThrows { Invoke-SystemCleanupSearchCompaction $serverContext } 'blocked on server'
|
|
$script:serverAssessmentRan=$false
|
|
Invoke-SystemCleanupCategory $serverContext 'ShadowCopies' { $script:serverAssessmentRan=$true }
|
|
Assert-Cleanup (-not $script:serverAssessmentRan -and -not $serverContext.Stats.ShadowCopies.Enabled -and $serverContext.Stats.ShadowCopies.Status -eq 'Blocked on server' -and $null -eq $serverContext.Stats.ShadowCopies.CandidateBytes) 'A default-disabled server operation must be listed without assessment.'
|
|
& {
|
|
function Get-CimInstance { param($ClassName) if ($ClassName -eq 'Win32_OperatingSystem') { [pscustomobject]@{ProductType=3; Caption='Fixture Server'} } }
|
|
function Invoke-SystemCleanupDiskCleanup { throw 'SERVER GUARD BYPASSED' }
|
|
function Invoke-SystemCleanupShadows { throw 'SERVER GUARD BYPASSED' }
|
|
function Invoke-SystemCleanupSearchCompaction { throw 'SERVER GUARD BYPASSED' }
|
|
function Invoke-SystemCleanupProcess { throw 'SERVER GUARD BYPASSED' }
|
|
# Substitute inert actions so the expanded report cannot inspect host paths.
|
|
$dispatcher=${function:Invoke-SystemCleanupCategory}
|
|
$script:assessed=@()
|
|
function Invoke-SystemCleanupCategory {
|
|
param($Context,$Name,$Action)
|
|
& $dispatcher $Context $Name { $script:assessed += $Name }
|
|
}
|
|
$o=Get-SystemCleanupOptions
|
|
foreach ($key in @($o.Keys)) { if ($o[$key] -is [bool]) { $o[$key]=$false } }
|
|
$o.ReportOnly=$true
|
|
foreach ($name in $blocked) { if ($name -ne 'DiskCleanup') { $o[$name]=$true } }
|
|
$result = @(Invoke-SystemCleanup $o)
|
|
Assert-Cleanup ($result.Count -eq 22 -and @($result | Where-Object Status -eq 'Blocked on server').Count -eq $blocked.Count) 'Server report must list every blocked category.'
|
|
Assert-Cleanup (@($script:assessed | Where-Object { $_ -in $blocked }).Count -eq 0) 'Server report must not assess blocked categories.'
|
|
}
|
|
|
|
# None is disabled in reports and apply; every nonempty preset remains blocked
|
|
# on both server types. No host inventories, registry operations or native calls.
|
|
foreach ($server in @($false, $true)) {
|
|
foreach ($reportOnly in @($false, $true)) {
|
|
foreach ($presetName in $expectedPresets.Keys) {
|
|
& {
|
|
$CleanupDiskCleanupItems = $presetName
|
|
$c = New-CleanupContext -Server $server -ReportOnly $reportOnly
|
|
$script:ran = $false
|
|
Invoke-SystemCleanupCategory $c 'DiskCleanup' { $script:ran = $true }
|
|
$shouldRun = -not $server -and ($reportOnly -or $presetName -ne 'None')
|
|
Assert-Cleanup ($script:ran -eq $shouldRun) "Incorrect Disk Cleanup dispatch: $presetName / server=$server / report=$reportOnly"
|
|
if ($reportOnly) {
|
|
Assert-Cleanup ($c.Stats.DiskCleanup.Enabled -eq ($presetName -ne 'None')) 'Disk Cleanup enablement must follow its selection.'
|
|
Assert-Cleanup ($c.Stats.DiskCleanup.Setting -ceq "CleanupDiskCleanupItems=$presetName") 'Report must identify the real operator setting.'
|
|
if ($server) { Assert-Cleanup ($c.Stats.DiskCleanup.Status -eq 'Blocked on server') 'Presets must not bypass the server block.' }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
& {
|
|
$CleanupDiskCleanupItems = 'None'
|
|
$c = New-CleanupContext
|
|
function Get-ChildItem { throw 'None must not access the registry.' }
|
|
function Test-SystemCleanupAppRunning { throw 'None must not probe native cleanup.' }
|
|
function Invoke-SystemCleanupProcess { throw 'None must not launch cleanmgr.' }
|
|
$script:messages = @()
|
|
Invoke-SystemCleanupCategory $c 'DiskCleanup' { Invoke-SystemCleanupDiskCleanup $c }
|
|
Write-SystemCleanupReport $c
|
|
$report = $script:messages -join "`n"
|
|
Assert-Cleanup ($report -match '(?s)DISABLED -.*DiskCleanup \[CleanupDiskCleanupItems=None\].*No handlers selected') 'None must appear in the disabled report section with a clear explanation.'
|
|
Assert-Cleanup ($report -match 'items not selected.*Previous Installations' -and $report -notmatch 'CleanupDiskCleanup=') 'None should report unselected handlers without advertising the removed boolean.'
|
|
$c.Options.ReportOnly = $false
|
|
Invoke-SystemCleanupDiskCleanup $c
|
|
Assert-Cleanup ($c.Errors -eq 0) 'None must not attempt native cleanup, even through the helper directly.'
|
|
}
|
|
|
|
# File ages, literal brackets, nested fresh files, no changes in preview.
|
|
$root=Join-Path $testRoot 'temps'
|
|
$old=New-CleanupFixture 'temps\old[1].tmp'
|
|
$fresh=New-CleanupFixture 'temps\parent\fresh.tmp' 'fresh' 0
|
|
$nestedOld=New-CleanupFixture 'temps\parent\old.tmp'
|
|
[IO.Directory]::SetLastWriteTimeUtc((Split-Path -Parent $fresh), [datetime]::UtcNow.AddDays(-90))
|
|
$cutoff=[datetime]::UtcNow.AddDays(-7)
|
|
$c=New-CleanupContext
|
|
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
|
|
Assert-Cleanup ($c.Stats.SystemTemp.CandidateFiles -eq 2 -and $c.Stats.SystemTemp.RemovedFiles -eq 0) 'Preview counts incorrect.'
|
|
Assert-Cleanup ((Test-Path -LiteralPath $old) -and (Test-Path -LiteralPath $nestedOld) -and (Test-Path -LiteralPath $fresh)) 'Preview changed files.'
|
|
$c=New-CleanupContext -ReportOnly $false
|
|
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
|
|
Assert-Cleanup (-not (Test-Path -LiteralPath $old) -and -not (Test-Path -LiteralPath $nestedOld) -and (Test-Path -LiteralPath $fresh)) 'Age/leaf deletion failure.'
|
|
Assert-Cleanup ($c.Stats.SystemTemp.RemovedFiles -eq 2) 'Removed files were not counted.'
|
|
|
|
# Disabled categories get independent report estimates, even when files overlap an
|
|
# enabled category later in the run. Apply mode still ignores disabled categories.
|
|
$potentialRoot=Join-Path $testRoot 'potential'
|
|
$potentialOriginal=New-CleanupFixture 'potential\install.exe' 'abc'
|
|
$potentialDuplicate=New-CleanupFixture 'potential\install (1).exe' 'abc'
|
|
$potentialRecent=New-CleanupFixture 'potential\recent.exe' 'fresh' 0
|
|
$c=New-CleanupContext
|
|
$c.Options.DownloadedExecutables=$false; $c.Options.DuplicateDownloads=$true
|
|
Invoke-SystemCleanupCategory $c 'DownloadedExecutables' { Clear-SystemCleanupTree $c 'DownloadedExecutables' $potentialRoot $cutoff -Include @('*.exe') }
|
|
Invoke-SystemCleanupCategory $c 'DuplicateDownloads' { Remove-SystemCleanupDuplicates $c $potentialRoot $cutoff }
|
|
Assert-Cleanup (-not $c.Stats.DownloadedExecutables.Enabled -and $c.Stats.DownloadedExecutables.CandidateFiles -eq 2 -and $c.Stats.DownloadedExecutables.CandidateBytes -eq 6) 'Disabled download estimate is missing or includes recent files.'
|
|
Assert-Cleanup ($c.Stats.DuplicateDownloads.Enabled -and $c.Stats.DuplicateDownloads.CandidateFiles -eq 1 -and $c.Stats.DuplicateDownloads.CandidateBytes -eq 3) 'Disabled preview consumed an enabled category candidate.'
|
|
Assert-Cleanup (-not $c.Options.DownloadedExecutables -and (Test-Path -LiteralPath $potentialDuplicate)) 'Preview enabled a disabled option or deleted data.'
|
|
$totals=Get-SystemCleanupReportTotals $c
|
|
Assert-Cleanup ($totals.EnabledBytes -eq 3 -and $totals.EnabledFiles -eq 1 -and $totals.AdditionalDisabledBytes -eq 3 -and $totals.AdditionalDisabledFiles -eq 1) 'Overlapping report totals double-counted a file.'
|
|
$script:messages=@()
|
|
Write-SystemCleanupReport $c
|
|
$report=$script:messages -join "`n"
|
|
Assert-Cleanup ($report.IndexOf('ENABLED -') -lt $report.IndexOf('DISABLED -') -and $report.IndexOf('DuplicateDownloads [CleanupDuplicateDownloads=true]') -lt $report.IndexOf('DISABLED -') -and $report.IndexOf('DownloadedExecutables [CleanupDownloadedExecutables=false]') -gt $report.IndexOf('DISABLED -')) 'Enabled and disabled report groups are unclear or misplaced.'
|
|
$c=New-CleanupContext -ReportOnly $false
|
|
$script:disabledRan=$false
|
|
Invoke-SystemCleanupCategory $c 'DownloadedExecutables' { $script:disabledRan=$true; Clear-SystemCleanupTree $c 'DownloadedExecutables' $potentialRoot $cutoff -Include @('*.exe') }
|
|
Assert-Cleanup (-not $script:disabledRan -and (Test-Path -LiteralPath $potentialOriginal) -and (Test-Path -LiteralPath $potentialDuplicate) -and (Test-Path -LiteralPath $potentialRecent)) 'Apply mode ran a disabled category.'
|
|
|
|
$outside=New-CleanupFixture 'outside\preserved.tmp'
|
|
Assert-Cleanup (-not (Test-SystemCleanupPath $outside $root)) 'Containment check accepted an outside file.'
|
|
Assert-Cleanup (-not (Test-SystemCleanupPath 'C:\Windows' 'C:\')) 'Drive-root cleanup must be rejected.'
|
|
$junction=Join-Path $root 'linked'
|
|
$null=New-Item -ItemType Junction -Path $junction -Target (Split-Path -Parent $outside)
|
|
try {
|
|
Assert-Cleanup (-not (Test-SystemCleanupPath (Join-Path $junction 'preserved.tmp') $root)) 'Linked ancestor was accepted.'
|
|
$c=New-CleanupContext -ReportOnly $false
|
|
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
|
|
Assert-Cleanup (Test-Path -LiteralPath $outside) 'Cleanup followed junction outside the target.'
|
|
} finally { [IO.Directory]::Delete($junction, $false) }
|
|
$locked=New-CleanupFixture 'temps\locked.tmp'
|
|
$lock=[IO.File]::Open($locked, 'Open', 'ReadWrite', 'None')
|
|
try {
|
|
$c=New-CleanupContext -ReportOnly $false
|
|
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
|
|
Assert-Cleanup ((Test-Path -LiteralPath $locked) -and $c.Stats.SystemTemp.FailedFiles -eq 1) 'Locked files must be retained and counted.'
|
|
} finally { $lock.Dispose() }
|
|
|
|
# Same length is not the same content, and extensions must match.
|
|
$null=New-CleanupFixture 'downloads\a.txt' 'abc'
|
|
$same=New-CleanupFixture 'downloads\a (1).txt' 'abc'
|
|
$different=New-CleanupFixture 'downloads\a (2).txt' 'xyz'
|
|
$extension=New-CleanupFixture 'downloads\a (1).csv' 'abc'
|
|
$recent=New-CleanupFixture 'downloads\a (3).txt' 'abc' 0
|
|
$c=New-CleanupContext -ReportOnly $false; $c.Options.DuplicateDownloads=$true
|
|
Invoke-SystemCleanupCategory $c 'DuplicateDownloads' { Remove-SystemCleanupDuplicates $c (Join-Path $testRoot 'downloads') $cutoff }
|
|
Assert-Cleanup (-not (Test-Path -LiteralPath $same) -and (Test-Path -LiteralPath $different) -and (Test-Path -LiteralPath $extension) -and (Test-Path -LiteralPath $recent)) 'Duplicate matching/retention failure.'
|
|
|
|
# Entire backup retained when a nested file is recent; old complete unit removed.
|
|
$backupOld=New-CleanupFixture 'backups\phone\old.dat'
|
|
$backupFresh=New-CleanupFixture 'backups\phone\nested\new.dat' 'new' 0
|
|
$bundle=Split-Path -Parent $backupOld
|
|
[IO.Directory]::SetLastWriteTimeUtc($bundle, [datetime]::UtcNow.AddDays(-60))
|
|
$c=New-CleanupContext -ReportOnly $false; $c.Options.ITunesBackups=$true
|
|
Invoke-SystemCleanupCategory $c 'ITunesBackups' { Remove-SystemCleanupBundle $c 'ITunesBackups' $bundle $cutoff }
|
|
Assert-Cleanup ((Test-Path -LiteralPath $backupOld) -and (Test-Path -LiteralPath $backupFresh)) 'Recent backup was partially cleaned.'
|
|
[IO.File]::SetLastWriteTimeUtc($backupFresh,[datetime]::UtcNow.AddDays(-60))
|
|
[IO.Directory]::SetLastWriteTimeUtc((Split-Path -Parent $backupFresh),[datetime]::UtcNow.AddDays(-60))
|
|
$backupLock=[IO.File]::Open($backupFresh,'Open','ReadWrite','None')
|
|
try {
|
|
$c=New-CleanupContext -ReportOnly $false; $c.Options.ITunesBackups=$true
|
|
Invoke-SystemCleanupCategory $c 'ITunesBackups' { Remove-SystemCleanupBundle $c 'ITunesBackups' $bundle $cutoff }
|
|
Assert-Cleanup ((Test-Path -LiteralPath $backupOld) -and (Test-Path -LiteralPath $backupFresh)) 'Locked backup was partially cleaned.'
|
|
} finally { $backupLock.Dispose() }
|
|
$c=New-CleanupContext -ReportOnly $false; $c.Options.ITunesBackups=$true
|
|
Invoke-SystemCleanupCategory $c 'ITunesBackups' { Remove-SystemCleanupBundle $c 'ITunesBackups' $bundle $cutoff }
|
|
Assert-Cleanup (-not (Test-Path -LiteralPath $bundle)) 'Old backup unit was not completely removed.'
|
|
|
|
# $I metadata controls retention, NOT the payload's old modification time.
|
|
$recycle=Join-Path $testRoot 'recycle'
|
|
foreach ($case in @(@{Id='old'; Days=60; Version=2},@{Id='recent'; Days=0; Version=1},@{Id='unknown'; Days=60; Version=99})) {
|
|
$meta=New-CleanupFixture ('recycle\S-1-5-21-fixture\$I'+$case.Id) 'placeholder'
|
|
$null=New-CleanupFixture ('recycle\S-1-5-21-fixture\$R'+$case.Id) 'data'
|
|
$originalPath=[Text.Encoding]::Unicode.GetBytes("C:\fixture.txt`0")
|
|
$length=if ($case.Version -eq 1) {544} else {28+$originalPath.Length}
|
|
$bytes=New-Object byte[] $length
|
|
[BitConverter]::GetBytes([long]$case.Version).CopyTo($bytes,0)
|
|
[BitConverter]::GetBytes([long]4).CopyTo($bytes,8)
|
|
[BitConverter]::GetBytes([datetime]::UtcNow.AddDays(-$case.Days).ToFileTimeUtc()).CopyTo($bytes,16)
|
|
if ($case.Version -eq 1) { $originalPath.CopyTo($bytes,24) }
|
|
else {
|
|
[BitConverter]::GetBytes([uint32]($originalPath.Length/2)).CopyTo($bytes,24)
|
|
$originalPath.CopyTo($bytes,28)
|
|
}
|
|
[IO.File]::WriteAllBytes($meta,$bytes)
|
|
}
|
|
$c=New-CleanupContext -ReportOnly $false; $c.Options.RecycleBin=$true
|
|
Invoke-SystemCleanupCategory $c 'RecycleBin' { Clear-SystemCleanupRecycleBin $c $recycle $cutoff }
|
|
Assert-Cleanup (-not (Test-Path -LiteralPath (Join-Path $recycle 'S-1-5-21-fixture\$Rold')) -and -not (Test-Path -LiteralPath (Join-Path $recycle 'S-1-5-21-fixture\$Iold'))) 'Old recycled pair not removed.'
|
|
foreach ($id in @('recent','unknown')) {
|
|
Assert-Cleanup ((Test-Path -LiteralPath (Join-Path $recycle ('S-1-5-21-fixture\$I'+$id))) -and (Test-Path -LiteralPath (Join-Path $recycle ('S-1-5-21-fixture\$R'+$id)))) "Unsafe recycle deletion: $id"
|
|
}
|
|
$truncated=New-CleanupFixture 'truncated-recycle-metadata' 'data'
|
|
[IO.File]::WriteAllBytes($truncated, [byte[]]@(2,0,0,0,0,0,0,0))
|
|
Assert-CleanupThrows { Get-SystemCleanupRecycleDate $truncated } 'Truncated'
|
|
|
|
# Native failure is observable; preview never starts a process.
|
|
& {
|
|
$script:starts=0
|
|
function Start-Process { param($FilePath,$ArgumentList,$WindowStyle,[switch]$Wait,[switch]$PassThru)
|
|
$script:starts++; Assert-Cleanup ($Wait -and $PassThru -and $WindowStyle -eq 'Hidden') 'Native operations must wait, capture exit status, and hide the window.'
|
|
[pscustomobject]@{ExitCode=5}
|
|
}
|
|
$c=New-CleanupContext
|
|
Invoke-SystemCleanupProcess $c 'powercfg.exe' '/hibernate off'
|
|
Assert-Cleanup ($script:starts -eq 0) 'Report mode launched a native process.'
|
|
$c.Options.ReportOnly=$false
|
|
Assert-CleanupThrows { Invoke-SystemCleanupProcess $c 'powercfg.exe' '/hibernate off' } 'exit code 5'
|
|
}
|
|
# cleanmgr only writes selected handlers in an unused slot; finally restores after failure.
|
|
& {
|
|
$script:events=@(); $script:nativeFailure=$false
|
|
function Test-SystemCleanupAppRunning { return $false }
|
|
function Get-ChildItem {
|
|
param($LiteralPath)
|
|
foreach ($name in @('Thumbnail Cache','Previous Installations')) {
|
|
$key=[pscustomobject]@{PSChildName=$name; PSPath=('fixture:\'+$name)}
|
|
$key | Add-Member ScriptMethod GetValueNames { @('StateFlags1000') }
|
|
$key
|
|
}
|
|
}
|
|
function New-ItemProperty { param($LiteralPath,$Name,$Value,$PropertyType) $script:events += "write:$LiteralPath/$Name=$Value" }
|
|
function Remove-ItemProperty { param($LiteralPath,$Name) $script:events += "remove:$LiteralPath/$Name" }
|
|
function Invoke-SystemCleanupProcess { param($Context,$FileName,$Arguments) $script:events += "run:$FileName $Arguments"; if ($script:nativeFailure) { throw 'Synthetic native failure' } }
|
|
$c=New-CleanupContext; $c.Options.DiskCleanupItems=@('Thumbnail Cache'); $c.Options.DiskCleanupPreset='Custom'
|
|
Invoke-SystemCleanupDiskCleanup $c
|
|
Assert-Cleanup ($script:events.Count -eq 0) 'Report mode wrote Disk Cleanup settings.'
|
|
$c.Options.ReportOnly=$false
|
|
foreach ($script:nativeFailure in @($false,$true)) {
|
|
$script:events=@()
|
|
if ($script:nativeFailure) { Assert-CleanupThrows { Invoke-SystemCleanupDiskCleanup $c } 'Synthetic native failure' }
|
|
else { Invoke-SystemCleanupDiskCleanup $c }
|
|
Assert-Cleanup ($script:events.Count -eq 3 -and $script:events[0] -eq 'write:fixture:\Thumbnail Cache/StateFlags1001=2' -and $script:events[1] -eq 'run:cleanmgr.exe /sagerun:1001' -and $script:events[2] -eq 'remove:fixture:\Thumbnail Cache/StateFlags1001') 'Disk Cleanup settings selection/restoration failed.'
|
|
}
|
|
}
|
|
# Snapshot deletion is exact-ID based and retains the newest system-volume snapshot.
|
|
& {
|
|
$script:commands=@()
|
|
function Get-CimInstance {
|
|
param($ClassName)
|
|
if ($ClassName -eq 'Win32_Volume') { [pscustomobject]@{DriveLetter=$env:SystemDrive; DeviceID='volume1'} }
|
|
else {
|
|
[pscustomobject]@{VolumeName='volume1'; InstallDate=[datetime]'2026-10-01'; ID='{11111111-1111-1111-1111-111111111111}'}
|
|
[pscustomobject]@{VolumeName='volume1'; InstallDate=[datetime]'2026-10-02'; ID='{22222222-2222-2222-2222-222222222222}'}
|
|
[pscustomobject]@{VolumeName='volume2'; InstallDate=[datetime]'2026-09-01'; ID='{33333333-3333-3333-3333-333333333333}'}
|
|
}
|
|
}
|
|
function Invoke-SystemCleanupProcess { param($Context,$FileName,$Arguments) $script:commands += "$FileName $Arguments" }
|
|
Invoke-SystemCleanupShadows (New-CleanupContext)
|
|
Assert-Cleanup ($script:commands.Count -eq 1 -and $script:commands[0] -match '/Shadow=\{11111111-' -and $script:commands[0] -notmatch '/Oldest') 'Incorrect VSS target selection.'
|
|
}
|
|
# Search always restores running state after failure, never changes startup settings.
|
|
& {
|
|
$savedProgramData=$env:ProgramData
|
|
$null=New-CleanupFixture 'search\Microsoft\Search\Data\Applications\Windows\Windows.edb'
|
|
try {
|
|
$env:ProgramData=Join-Path $testRoot 'search'
|
|
$script:serviceEvents=@()
|
|
function Get-Service {
|
|
param($Name)
|
|
$s=[pscustomobject]@{Status=$script:originalServiceStatus}
|
|
$s | Add-Member ScriptMethod WaitForStatus { param($Status,$Timeout) $script:serviceEvents += 'wait' }
|
|
return $s
|
|
}
|
|
function Stop-Service { param($Name) $script:serviceEvents += 'stop' }
|
|
function Start-Service { param($Name) $script:serviceEvents += 'start' }
|
|
function Set-Service { throw 'Startup configuration must be preserved.' }
|
|
function Invoke-SystemCleanupProcess { param($Context,$FileName,$Arguments) $script:serviceEvents += 'compact'; throw 'Synthetic compaction failure' }
|
|
foreach ($script:originalServiceStatus in @('Running','Stopped')) {
|
|
$script:serviceEvents=@()
|
|
$c=New-CleanupContext -ReportOnly $false
|
|
Assert-CleanupThrows { Invoke-SystemCleanupSearchCompaction $c } 'Synthetic compaction failure'
|
|
$expected=if ($script:originalServiceStatus -eq 'Running') { 'stop,wait,compact,start' } else { 'compact' }
|
|
Assert-Cleanup (($script:serviceEvents -join ',') -eq $expected) 'Search service restoration failed.'
|
|
}
|
|
$script:serviceEvents=@()
|
|
Invoke-SystemCleanupSearchCompaction (New-CleanupContext)
|
|
Assert-Cleanup ($script:serviceEvents.Count -eq 0) 'Preview changed Search service state.'
|
|
} finally { $env:ProgramData=$savedProgramData }
|
|
}
|
|
# Entire entry point with mixed enablement in preview. All mutation APIs fail
|
|
# the test if called. Every environment path and inventory points at inert fixtures.
|
|
& {
|
|
$savedEnvironment=@{SystemRoot=$env:SystemRoot; SystemDrive=$env:SystemDrive; ProgramData=$env:ProgramData}
|
|
$previewRoot=Join-Path $testRoot 'preview'
|
|
$null=New-CleanupFixture 'preview\Windows\Temp\old.tmp'
|
|
$null=New-CleanupFixture 'preview\Windows\Temp\CbsPersist_fixture.log'
|
|
$null=New-CleanupFixture 'preview\Users\Alice\AppData\Local\Temp\old.tmp'
|
|
$null=New-CleanupFixture 'preview\Users\Alice\Downloads\install.exe'
|
|
$null=New-CleanupFixture 'preview\hiberfil.sys'
|
|
foreach ($exe in @('powercfg.exe','schtasks.exe','esentutl.exe','vssadmin.exe','cleanmgr.exe')) { $null=New-CleanupFixture ('preview\Windows\System32\'+$exe) 'inert, never executed' }
|
|
try {
|
|
$env:SystemRoot=Join-Path $previewRoot 'Windows'; $env:SystemDrive=$previewRoot
|
|
$env:ProgramData=Join-Path $previewRoot 'ProgramData'
|
|
function Get-CimInstance {
|
|
param($ClassName)
|
|
switch ($ClassName) {
|
|
Win32_OperatingSystem { [pscustomobject]@{ProductType=1; Caption='Fixture Client'} }
|
|
Win32_UserProfile { [pscustomobject]@{Special=$false; LocalPath=(Join-Path $previewRoot 'Users\Alice')} }
|
|
Win32_Volume { [pscustomobject]@{DriveLetter=$env:SystemDrive; DeviceID='volume1'} }
|
|
Win32_ShadowCopy {
|
|
[pscustomobject]@{VolumeName='volume1'; InstallDate=[datetime]'2026-10-01'; ID='{11111111-1111-1111-1111-111111111111}'}
|
|
[pscustomobject]@{VolumeName='volume1'; InstallDate=[datetime]'2026-10-02'; ID='{22222222-2222-2222-2222-222222222222}'}
|
|
}
|
|
}
|
|
}
|
|
function Test-SystemCleanupAppRunning { return $false }
|
|
function Get-Service { [pscustomobject]@{Status='Stopped'} }
|
|
function Remove-Item { throw 'PREVIEW MUTATION: Remove-Item' }
|
|
function New-ItemProperty { throw 'PREVIEW MUTATION: registry write' }
|
|
function Remove-ItemProperty { throw 'PREVIEW MUTATION: registry removal' }
|
|
function Start-Service { throw 'PREVIEW MUTATION: start service' }
|
|
function Stop-Service { throw 'PREVIEW MUTATION: stop service' }
|
|
function Delete-DeliveryOptimizationCache { throw 'PREVIEW MUTATION: delivery cache' }
|
|
function Start-Process { throw 'PREVIEW MUTATION: native program' }
|
|
$o=Get-SystemCleanupOptions
|
|
$result=@(Invoke-SystemCleanup $o)
|
|
Assert-Cleanup ($result.Count -eq 22 -and @($result | Where-Object Status -ne 'Preview').Count -eq 0) "Full preview did not cover every category (count=$($result.Count))."
|
|
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'DownloadedExecutables' -and -not $_.Enabled -and $_.CandidateFiles -eq 1 }).Count -eq 1) 'Default-disabled downloads were not assessed by the entry point.'
|
|
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'ComponentStore' -and -not $_.Enabled -and $null -eq $_.CandidateBytes -and $_.EstimateStatus -eq 'Not estimated' }).Count -eq 1) 'Unknown native savings must not be reported as zero.'
|
|
Assert-Cleanup (Test-Path -LiteralPath (Join-Path $env:SystemRoot 'Temp\old.tmp')) 'Full preview removed a fixture.'
|
|
function Test-SystemCleanupAppRunning { return $true }
|
|
function Get-Command { return $null }
|
|
$o.DiskCleanupItems=@(); $o.DiskCleanupPreset='None'
|
|
$result=@(Invoke-SystemCleanup $o)
|
|
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'RevitJournals' -and $_.Status -eq 'Skipped' }).Count -eq 1) 'An active application should skip cleanup, not fail the whole run.'
|
|
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'DeliveryOptimization' -and -not $_.Enabled -and $_.Status -eq 'Unavailable' -and $null -eq $_.CandidateBytes }).Count -eq 1) 'A missing optional feature must be reported as unavailable, not zero savings or a failed report.'
|
|
} finally {
|
|
$env:SystemRoot=$savedEnvironment.SystemRoot; $env:SystemDrive=$savedEnvironment.SystemDrive; $env:ProgramData=$savedEnvironment.ProgramData
|
|
}
|
|
}
|
|
Write-Host "PASS: $script:assertions offline cleanup assertions ($($PSVersionTable.PSVersion))."
|
|
} finally {
|
|
# Only this test's generated directory; links are removed non-recursively above.
|
|
$resolved=[IO.Path]::GetFullPath($testRoot)
|
|
$expectedParent=[IO.Path]::GetFullPath($env:TEMP).TrimEnd('\')+'\'
|
|
if (-not $resolved.StartsWith($expectedParent,[StringComparison]::OrdinalIgnoreCase) -or (Split-Path -Leaf $resolved) -notmatch '^SystemCleanupTests-[0-9a-f]{32}$') { throw 'Unsafe fixture cleanup path.' }
|
|
if (Test-Path -LiteralPath $resolved) { Remove-Item -LiteralPath $resolved -Recurse -Force }
|
|
}
|