fix more issues with the scrubber and product install status

This commit is contained in:
2026-10-30 15:35:38 -04:00
parent 0c614596f8
commit f2830cb10a
8 changed files with 474 additions and 59 deletions
@@ -0,0 +1,129 @@
#Requires -Version 5.1
$ErrorActionPreference = 'Stop'
if ($PSVersionTable.PSEdition -ne 'Desktop') { throw 'Run with Windows PowerShell 5.1.' }
$repo = Split-Path -Parent $PSScriptRoot
$testRoot = Join-Path $env:TEMP ('OfficeDiagnosticsTests-' + [guid]::NewGuid().ToString('N'))
$originalTemp = [IO.Path]::GetFullPath($env:TEMP).TrimEnd('\') + '\'
$nativePowerShell = Join-Path $env:windir 'System32\WindowsPowerShell\v1.0\powershell.exe'
$null = New-Item -ItemType Directory -Path $testRoot
$script:assertions = 0
function Assert-DiagnosticTest { param([bool]$Condition, [string]$Message) $script:assertions++; if (!$Condition) { throw $Message } }
function Read-DiagnosticAst {
param([string]$Path)
$tokens=$null; $errors=$null
$ast=[Management.Automation.Language.Parser]::ParseFile($Path,[ref]$tokens,[ref]$errors)
if ($errors.Count) { throw ($errors | Out-String) }
$ast
}
function Read-ZipText {
param($Archive,[string]$Name)
$reader=New-Object IO.StreamReader($Archive.GetEntry($Name).Open())
try { $reader.ReadToEnd() } finally { $reader.Dispose() }
}
$savedEnvironment=@{}
try {
$coreAst=Read-DiagnosticAst (Join-Path $repo 'Get-OfficeDeploymentDiagnostics.ps1')
$shimAst=Read-DiagnosticAst (Join-Path $repo 'rmm\Get-OfficeDeploymentDiagnostics.ps1')
Assert-DiagnosticTest (!$coreAst.ParamBlock -and !$shimAst.ParamBlock) 'RMM scripts must not introduce script parameters.'
$definitions=@($coreAst.FindAll({param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst]},$false))
foreach ($definition in $definitions) { . ([scriptblock]::Create($definition.Extent.Text)) }
Add-Type -AssemblyName System.IO.Compression.FileSystem
$source=Join-Path $testRoot 'source'; $null=New-Item -ItemType Directory -Path "$source\nested\deep" -Force
[IO.File]::WriteAllText("$source\live.log",'fixture with Unicode: caf'+[char]0xE9)
[IO.File]::WriteAllText("$source\install.xml",'<Configuration />')
[IO.File]::WriteAllText("$source\media.dat",'not diagnostics')
[IO.File]::WriteAllText("$source\nested\child.log",'child log')
[IO.File]::WriteAllText("$source\nested\deep\excluded.log",'too deep')
$issues=New-Object 'Collections.Generic.List[string]'
$files=@(Get-OfficeDiagnosticFiles $source @('*.log','install.xml') ([datetime]::UtcNow.AddHours(-1)) 1 $issues)
Assert-DiagnosticTest ($files.Count -eq 3 -and !@($files | Where-Object {$_.Name -in @('media.dat','excluded.log')}).Count) 'Only requested diagnostics within the recursion depth may be collected.'
Assert-DiagnosticTest (@(Get-OfficeDiagnosticFiles $source @('*.log') ([datetime]::UtcNow.AddHours(1)) 1 $issues).Count -eq 0) 'Old files must be excluded by the time window.'
$before=(Get-FileHash -LiteralPath "$source\live.log").Hash
$held=[IO.File]::Open("$source\live.log",[IO.FileMode]::Open,[IO.FileAccess]::ReadWrite,[IO.FileShare]::ReadWrite)
try { New-OfficeDiagnosticArchive "$testRoot\fixture.zip" ($files + $files) @{CurrentStateOnly=$true} $issues }
finally { $held.Dispose() }
$zip=[IO.Compression.ZipFile]::OpenRead("$testRoot\fixture.zip")
try {
$manifest=Read-ZipText $zip 'manifest.json' | ConvertFrom-Json
Assert-DiagnosticTest ($manifest.Count -eq 3 -and @($manifest | Where-Object {$_.Status -notlike 'Captured*'}).Count -eq 0) 'Duplicate paths must be collected once, including a log open by another writer.'
$entry=@($manifest | Where-Object {$_.Source -eq "$source\live.log"})[0]
Assert-DiagnosticTest ((Read-ZipText $zip $entry.Entry) -eq [IO.File]::ReadAllText("$source\live.log")) 'Captured bytes must preserve source encoding/content.'
Assert-DiagnosticTest ($null -ne $zip.GetEntry('endpoint.json') -and $null -ne $zip.GetEntry('collection-issues.json')) 'Metadata and collection omissions must accompany the logs.'
} finally { $zip.Dispose() }
Assert-DiagnosticTest ((Get-FileHash -LiteralPath "$source\live.log").Hash -eq $before) 'Source logs must remain unchanged.'
$big=[IO.File]::Create("$source\oversize.log"); try {$big.SetLength(64MB+1)} finally {$big.Dispose()}
$issues=New-Object 'Collections.Generic.List[string]'
New-OfficeDiagnosticArchive "$testRoot\limits.zip" @((Get-Item "$source\oversize.log")) @{} $issues
Assert-DiagnosticTest ($issues.Count -eq 1 -and $issues[0] -match 'Collection limit') 'Oversize logs must be reported as omitted, not silently lost.'
# Exercise the actual Run-Script helper with mocked live downloads and queries.
# The core's registry reader is replaced only in the fixture downloaded by this test.
$toolsAst=Read-DiagnosticAst (Join-Path $repo 'Tools.ps1')
$runDefinition=$toolsAst.Find({param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Run-Script'},$false)
. ([scriptblock]::Create($runDefinition.Extent.Text))
function IsURLValid { param($URL) $true }
function Download-File { param($URL) Assert-DiagnosticTest ($URL -like '*/Get-OfficeDeploymentDiagnostics.ps1') 'Caller must request the diagnostic core.'; "$testRoot\downloaded-core.ps1" }
$fixtureCore=($definitions | Where-Object {$_.Name -ne 'Get-OfficeDiagnosticRegistry'} | ForEach-Object {$_.Extent.Text}) -join "`r`n"
$fixtureCore += "`r`nInvoke-OfficeDiagnosticCollection"
[IO.File]::WriteAllText("$testRoot\downloaded-core.ps1",$fixtureCore)
function New-Object {
param([string]$TypeName,[object[]]$ArgumentList)
if ($TypeName -eq 'Security.Principal.WindowsPrincipal') {
$principal=[pscustomobject]@{}
$principal | Add-Member ScriptMethod IsInRole { $true }
return $principal
}
if ($TypeName -eq 'Net.WebClient') {
$client=[pscustomobject]@{}
$client | Add-Member ScriptMethod DownloadString {param($Url) if ($Url -notlike '*/Get-OfficeDeploymentDiagnostics.ps1') {throw "Unexpected URL $Url"}; [IO.File]::ReadAllText("$testRoot\downloaded-core.ps1")}
return $client
}
Microsoft.PowerShell.Utility\New-Object @PSBoundParameters
}
function Get-OfficeDiagnosticRegistry { [pscustomobject]@{Name='ProductReleaseIds';Value='FixtureOffice'} }
function Get-CimInstance {
param($ClassName,$Filter,$ErrorAction)
switch ($ClassName) {
Win32_OperatingSystem { [pscustomobject]@{Caption='Fixture';LastBootUpTime=[datetime]'2026-10-30T08:00:00'} }
Win32_UserProfile { [pscustomobject]@{SID='S-1-fixture';LocalPath="$testRoot\other-user";Loaded=$false;Special=$false} }
Win32_Process { [pscustomobject]@{Name='powershell.exe';ProcessId=456;SessionId=2;CommandLine='powershell.exe -File C:\Temp\GetHelpElevated\fixture\Run.ps1'} }
Win32_Service { [pscustomobject]@{Name='ClickToRunSvc';State='Running'} }
default { throw "Unexpected CIM query $ClassName" }
}
}
function Invoke-CimMethod { [pscustomobject]@{Domain='Fixture';User='OtherUser';ReturnValue=0} }
function Get-ScheduledTask { @() }
foreach ($name in @('TEMP','LOCALAPPDATA','ProgramData','windir','COMPUTERNAME')) { $savedEnvironment[$name]=[Environment]::GetEnvironmentVariable($name,'Process') }
$env:TEMP="$testRoot\temp"; $env:LOCALAPPDATA="$testRoot\current-user"; $env:ProgramData="$testRoot\programdata"; $env:windir="$testRoot\Windows"; $env:COMPUTERNAME='FIXTURE'
foreach ($directory in @($env:TEMP,"$testRoot\other-user\AppData\Local\DAFs","$env:windir\Temp","$env:windir\SystemTemp\EmberkomOfficeDeployment\run\ODT")) { $null=New-Item -ItemType Directory -Path $directory -Force }
[IO.File]::WriteAllText("$testRoot\other-user\AppData\Local\DAFs\cse.amplify.diagaction.gethelp.officeuninstallalda_fixture.log",'Report from another user')
[IO.File]::WriteAllText("$env:windir\Temp\FIXTURE-20261030-0900.log",'Native install fixture')
[IO.File]::WriteAllText("$env:windir\SystemTemp\EmberkomOfficeDeployment\run\install.xml",'<Configuration />')
[IO.File]::WriteAllText("$env:windir\SystemTemp\EmberkomOfficeDeployment\run\ODT\setup.exe",'Excluded executable fixture')
$result=@(Run-Script -LivePSScript Get-OfficeDeploymentDiagnostics)
$bundle=@(Get-ChildItem -LiteralPath "$env:ProgramData\Emberkom\Logs\OfficeDiagnostics" -Filter '*.zip')
Assert-DiagnosticTest ($bundle.Count -eq 1 -and ($result -join "`n") -match 'Office diagnostic ZIP') 'The real RMM loader must execute the diagnostic core and return its ZIP path.'
$zip=[IO.Compression.ZipFile]::OpenRead($bundle[0].FullName)
try {
$manifest=Read-ZipText $zip 'manifest.json' | ConvertFrom-Json
$report=Read-ZipText $zip 'endpoint.json' | ConvertFrom-Json
Assert-DiagnosticTest (@($manifest | Where-Object {$_.Source -like '*other-user*DAFs*'}).Count -eq 1) 'DAF reports from profiles other than the caller must be captured.'
Assert-DiagnosticTest (@($manifest | Where-Object {$_.Source -like '*FIXTURE-20261030-0900.log'}).Count -eq 1) 'Native logs must be captured.'
Assert-DiagnosticTest (@($manifest | Where-Object {$_.Source -like '*install.xml'}).Count -eq 1 -and !@($manifest | Where-Object {$_.Source -like '*.exe'}).Count) 'Archive configurations but never installation media.'
Assert-DiagnosticTest ($report.Workers[0].Owner -eq 'Fixture\OtherUser' -and $report.Workers[0].SessionId -eq 2) 'Worker ownership and session must be recorded.'
Assert-DiagnosticTest ($report.OfficeRegistry[0].Value -eq 'FixtureOffice') 'Current Office state must be recorded separately from historical logs.'
} finally { $zip.Dispose() }
# Core failures must signal failure to RMM instead of claiming a ZIP was created.
$entry=$coreAst.EndBlock.Statements[-1].Extent.Text
[IO.File]::WriteAllText("$testRoot\failure.ps1", "function Invoke-OfficeDiagnosticCollection { throw 'Fixture collection failure' }`r`n$entry")
$ErrorActionPreference='Continue'
try { & $nativePowerShell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$testRoot\failure.ps1" *> "$testRoot\failure-output.log" }
finally { $ErrorActionPreference='Stop' }
Assert-DiagnosticTest ($LASTEXITCODE -eq 1) 'A failed diagnostic collection must exit 1.'
Write-Output "PASS: $script:assertions diagnostic assertions. Queries/downloads mocked; no Office changes."
} finally {
foreach ($name in $savedEnvironment.Keys) { [Environment]::SetEnvironmentVariable($name,$savedEnvironment[$name],'Process') }
$resolved=[IO.Path]::GetFullPath($testRoot)
if (!$resolved.StartsWith($originalTemp,[StringComparison]::OrdinalIgnoreCase) -or (Split-Path -Leaf $resolved) -notlike 'OfficeDiagnosticsTests-*') { throw 'Unsafe test cleanup path.' }
Remove-Item -LiteralPath $resolved -Recurse -Force -ErrorAction Stop
}
+87 -18
View File
@@ -549,12 +549,13 @@ try {
[pscustomobject]@{DisplayName='Microsoft Office Professional Plus 2016'; WindowsInstaller=1}
if ($script:removalMode -eq 'msi-only') { return }
if ($script:removalStarted -and $script:removalMode -eq 'read-error') { throw 'Office inventory is unreadable' }
if (!$script:removalStarted -or $script:removalMode -eq 'remaining' -or ($script:removalMode -eq 'delayed' -and $script:removalChecks -le 3)) {
if (!$script:removalStarted -or $script:removalMode -in @('remaining','corrupt') -or ($script:removalMode -eq 'delayed' -and $script:removalChecks -le 3)) {
[pscustomobject]@{DisplayName='Microsoft Office Home and Business 2021 - en-us'}
}
}
function Get-OfficeClickToRunState { [pscustomobject]@{Present=($script:removalMode -eq 'orphan');SourceReferences=@();WorkingConfiguration=@($(if ($script:removalMode -eq 'stale') {'old-guid'}))} }
function Get-OfficeRemovalCorruptionEvidence { if ($script:removalMode -eq 'corrupt') { [pscustomobject]@{Path='fixture.log';Detail='REMOVEINSTALLATION InvalidDirectory'} } }
function Get-OfficeRemovalCorruptionEvidence { if ($script:removalMode -in @('corrupt','corrupt-gone')) { [pscustomobject]@{Path='fixture.log';Detail='REMOVEINSTALLATION InvalidDirectory'} } }
function Get-CimInstance { @() }
function Invoke-OfficeScrubRecovery { param($Media,$Workspace,$Reason) $script:scrubCalls++; Assert-OfficeTest (![string]::IsNullOrWhiteSpace($Reason)) 'Recovery must record its reason.'; return 3010 }
function Invoke-OfficeProcess {
param($FilePath,$Arguments,$LogPrefix)
@@ -566,9 +567,9 @@ try {
$removalPath = Join-Path $testRoot 'remove [literal].xml'
(New-OfficeRemovalConfiguration ([pscustomobject]@{OfficeAppShutdown='Force'})).Save($removalPath)
$media = [pscustomobject]@{Setup='inert-setup.exe'; RemovalConfig=$removalPath}
foreach ($script:removalMode in @('empty','orphan','msi-only','mixed','delayed','remaining','stale','corrupt','unknown-17004','read-error','fatal','reboot')) {
foreach ($script:removalMode in @('empty','orphan','msi-only','mixed','delayed','remaining','stale','corrupt','corrupt-gone','unknown-17004','read-error','fatal','reboot')) {
$script:removalChecks=0; $script:removalCalls=0; $script:removalStarted=$false; $script:scrubCalls=0
$script:removalCode = switch ($script:removalMode) { 'fatal' {1603}; 'reboot' {3010}; 'corrupt' {17004}; 'unknown-17004' {17004}; default {0} }
$script:removalCode = switch ($script:removalMode) { 'fatal' {1603}; 'reboot' {3010}; 'corrupt' {17004}; 'corrupt-gone' {17004}; 'unknown-17004' {17004}; default {0} }
if ($script:removalMode -eq 'remaining') {
Assert-OfficeTest ((Remove-OfficeSuite $media $testRoot) -eq 3010) 'Verified leftovers after ODT success must select scrub recovery.'
Assert-OfficeTest ($script:removalChecks -eq ((Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts + 2)) 'Remaining Click-to-Run products must be checked for the bounded registration interval.'
@@ -578,14 +579,14 @@ try {
Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'ODT Office removal failed.*automatic scrub was not selected'
} else {
$result = @(Remove-OfficeSuite $media $testRoot)
$expected = if ($script:removalMode -in @('reboot','corrupt','stale')) {3010} else {0}
$expected = if ($script:removalMode -in @('reboot','corrupt','corrupt-gone')) {3010} else {0}
Assert-OfficeTest ($result.Count -eq 1 -and $result[0] -eq $expected) 'Removal must return just its exit code; MSI products are deferred to installation.'
if ($script:removalMode -eq 'delayed') { Assert-OfficeTest ($script:removalChecks -eq 4) 'Removal must tolerate registry propagation delays.' }
if ($script:removalMode -eq 'reboot') { Assert-OfficeTest ($script:removalChecks -eq 1) 'A required restart must be surfaced before demanding registration cleanup.' }
}
$expectedCalls = if ($script:removalMode -in @('empty','msi-only')) {0} else {1}
Assert-OfficeTest ($script:removalCalls -eq $expectedCalls) 'Remove orphaned Click-to-Run state even without registered products, without rerunning ODT.'
Assert-OfficeTest ($script:scrubCalls -eq $(if ($script:removalMode -in @('corrupt','remaining','stale')) {1} else {0})) 'Only confirmed removal corruption or leftovers may trigger a single scrub.'
$expectedCalls = if ($script:removalMode -in @('empty','orphan','msi-only')) {0} else {1}
Assert-OfficeTest ($script:removalCalls -eq $expectedCalls) 'Run removal only for registered Click-to-Run products, never merely an orphaned service/registry key.'
Assert-OfficeTest ($script:scrubCalls -eq $(if ($script:removalMode -in @('corrupt','remaining')) {1} else {0})) 'Only failed removal with products remaining may trigger a single scrub; metadata or no products must not.'
}
}
& {
@@ -953,11 +954,41 @@ try {
Assert-OfficeThrows { Open-OfficeScrubWorkerHandle ([pscustomobject]@{ProcessId=$PID;CreationDate=[datetime]'2000-01-01'}) } 'Process identity changed'
} finally { if ($held) { $held.Dispose() }; $probe.Dispose() }
}
# Captured endpoint report: the launcher returned success, but the worker had
# already reported no supported products and was waiting in Console.ReadKey.
& {
$reports=Join-Path $testRoot 'DAFs'; $null=New-Item -ItemType Directory -Path $reports
$reportPath=Join-Path $reports 'cse.amplify.diagaction.gethelp.officeuninstallalda_fixture.log'
Copy-Item -LiteralPath (Join-Path $repo 'tests\fixtures\office\scrub-no-products.log') -Destination $reportPath
# Copy-Item preserves LastWriteTime; set both times to model a newly written report.
[IO.File]::SetCreationTimeUtc($reportPath,[datetime]::UtcNow)
[IO.File]::SetLastWriteTimeUtc($reportPath,[datetime]::UtcNow)
$worker=[pscustomobject]@{CreationDate=[datetime]::UtcNow.AddMinutes(-1)}
$result=@(Read-OfficeScrubWorkerReport $worker @($reports))
Assert-OfficeTest ($result.Count -eq 1 -and $result[0].Result -eq 'Failed' -and $result[0].Detail -eq 'There are no supported Office products installed.') 'Parse the actual failed scrub report, not the launcher success acknowledgment.'
$worker.CreationDate=[datetime]::UtcNow.AddMinutes(1)
Assert-OfficeTest (@(Read-OfficeScrubWorkerReport $worker @($reports)).Count -eq 0) 'An old report must never be attributed to a new worker.'
$worker.CreationDate=[datetime]::UtcNow.AddMinutes(-1)
Set-Content -LiteralPath $reportPath -Value 'Report: {"ExecutionResult":'
Assert-OfficeTest (@(Read-OfficeScrubWorkerReport $worker @($reports)).Count -eq 0) 'A report being written must not be interpreted as completed.'
Set-Content -LiteralPath $reportPath -Value 'Report: {"ExecutionResult":"Failed","TroubleshooterName":"OtherScenario"}'
Assert-OfficeTest (@(Read-OfficeScrubWorkerReport $worker @($reports)).Count -eq 0) 'Reports from another scenario must be ignored.'
function Invoke-CimMethod { [pscustomobject]@{ReturnValue=0;Sid='S-1-5-18'} }
$roots=@(Get-OfficeScrubReportRoots ([pscustomobject]@{ProcessId=9701}))
Assert-OfficeTest ($roots.Count -eq 2 -and $roots[0] -like '*systemprofile*\DAFs') 'SYSTEM reports must be sought in both system-profile locations.'
function Invoke-CimMethod { [pscustomobject]@{ReturnValue=0;Sid='S-1-fixture'} }
function Get-ItemPropertyValue { 'C:\Users\ScrubOwner' }
Assert-OfficeTest ((Get-OfficeScrubReportRoots ([pscustomobject]@{ProcessId=9701})) -eq 'C:\Users\ScrubOwner\AppData\Local\DAFs') 'Other worker reports must use that worker owner profile, not the RMM caller profile.'
}
# A background launch is pending. Workers must finish successfully and removal
# state must stay clean for the entire quiet interval; closing early is not success.
& {
$existing=[pscustomobject]@{Name='powershell.exe';ProcessId=8001;CreationDate=[datetime]'2026-10-29T12:00:00';CommandLine='powershell.exe -NoProfile'}
$fixtureScrubWorker=[pscustomobject]@{Name='powershell.exe';ProcessId=9701;CreationDate=[datetime]'2026-10-29T16:00:00';CommandLine='powershell.exe -File C:\Temp\GetHelpElevated\abc\Run.ps1'}
function Get-OfficeScrubReportRoots { @() }
function Read-OfficeScrubWorkerReport {
if ($script:waitMode -eq 'report-failed') { [pscustomobject]@{Result='Failed';Detail='There are no supported Office products installed.';Path='fixture-report.log'} }
}
function Get-OfficeScrubWorkers {
$script:waitPoll++
if ($script:waitMode -eq 'process-error') { throw 'Process inventory unreadable' }
@@ -979,22 +1010,28 @@ try {
if ($script:waitMode -eq 'remaining' -or ($script:waitMode -eq 'delayed' -and $script:waitPoll -le 4)) { [pscustomobject]@{DisplayName='Old Office'} }
}
function Get-OfficeClickToRunState {
$script:waitStateReads++
if ($script:waitMode -eq 'state-error') { throw 'Servicing state unreadable' }
[pscustomobject]@{SourceReferences=@($(if ($script:waitMode -eq 'stale') {'old-download'}));WorkingConfiguration=@()}
}
foreach ($script:waitMode in @('success','restart','delayed','quiet-reset','closed','failed','remaining','stale','no-worker','keypress','process-error','inventory-error','state-error','lost-handle')) {
$script:waitPoll=0; $script:disposed=0; $script:openCalls=0; $script:testSleeps=@()
if ($script:waitMode -in @('success','restart','delayed','quiet-reset')) {
foreach ($script:waitMode in @('success','restart','delayed','quiet-reset','closed','failed','remaining','stale','no-worker','keypress','process-error','inventory-error','report-failed','lost-handle')) {
$script:waitPoll=0; $script:disposed=0; $script:openCalls=0; $script:testSleeps=@(); $script:waitStateReads=0
if ($script:waitMode -in @('success','restart','delayed','quiet-reset','stale')) {
$result=@(Wait-OfficeScrubRemoval @($existing))
$expectedPolls=switch ($script:waitMode) { 'delayed' {11}; 'quiet-reset' {12}; default {9} }
Assert-OfficeTest ($result.Count -eq 0 -and $script:waitPoll -eq $expectedPolls) 'Background verification must wait for workers, delayed removal, and a continuous 60-second quiet interval without leaking output.'
} else {
$pattern=switch ($script:waitMode) { 'closed' {'exited unsuccessfully.*-1073741510'}; 'failed' {'exited unsuccessfully.*exit 1'}; 'process-error' {'Process inventory unreadable'}; 'inventory-error' {'Office inventory unreadable'}; 'state-error' {'Servicing state unreadable'}; 'lost-handle' {'Could not monitor scrub worker'}; default {'background removal did not finish verification'} }
if ($script:waitMode -eq 'keypress') { $pattern = 'Office registrations remaining: 0.*will not resume automatically.*success OR failure' }
if ($script:waitMode -eq 'report-failed') { $pattern = 'worker reported failure: There are no supported Office products installed.*fixture-report.log' }
Assert-OfficeThrows { Wait-OfficeScrubRemoval @($existing) } $pattern
if ($script:waitMode -eq 'keypress') { Assert-OfficeTest ($script:waitStateReads -eq 0) 'A live cleanup worker defers the servicing-state check; it does not prove stale state.' }
if ($script:waitMode -eq 'report-failed') { Assert-OfficeTest ($script:waitPoll -eq 1 -and !$script:testSleeps.Count) 'A terminal failed report must stop immediately, without a 30-minute keypress wait.' }
if ($script:waitMode -in @('remaining','stale','no-worker','keypress')) { Assert-OfficeTest (($script:testSleeps | Measure-Object -Sum).Sum -eq 1800) 'Unfinished background removal must stop after the restored 30-minute wait.' }
}
Assert-OfficeTest ($script:disposed -eq $(if ($script:waitMode -in @('process-error','no-worker','lost-handle')) {0} else {1})) 'Every acquired worker handle must be released on success and failure.'
Assert-OfficeTest ($script:openCalls -le 1) 'Polling must retain the same worker handle rather than reopening a possibly reused PID.'
Assert-OfficeTest ($script:waitStateReads -eq 0) 'Servicing metadata is not a scrub completion criterion.'
}
}
# A scrub requires both a successful scenario/process result and independently
@@ -1036,7 +1073,7 @@ try {
if ($script:scrubMode -eq 'remaining') { [pscustomobject]@{DisplayName='Leftover MSI Office';WindowsInstaller=1} }
if ($script:scrubMode -eq 'inventory-error') { throw 'Registry unreadable' }
}
function Assert-OfficeFreshInstallState { if ($script:scrubMode -eq 'stale') { throw 'Previous Click-to-Run state remains' } }
function Assert-OfficeRemovalComplete { if ($script:scrubMode -eq 'stale') { throw 'Removal verification failed' } }
foreach ($script:scrubMode in @('success','restart','download','bad-help','preexisting-worker','failure','not-found-66','not-found-68','empty','invalid-arguments','usage','background','background-no-worker','background-with-00','generic-success','text-error','background-bad-exit','background-error','contradictory','bad-exit','running','remaining','inventory-error','stale')) {
$workspace=Join-Path $testRoot ('scrub-result-' + $script:scrubMode); $null=[IO.Directory]::CreateDirectory($workspace)
$media=[pscustomobject]@{}; $script:scrubExit=0; $script:scrubOutput='00: Successfully completed this scenario.'; $script:backgroundWaits=0; $script:usageCalls=0
@@ -1060,7 +1097,7 @@ try {
$result=@(Invoke-OfficeScrubRecovery $media $workspace 'fixture corruption')
Assert-OfficeTest ($result.Count -eq 1 -and $result[0] -eq 3010 -and $media.ScrubAttempted -and $media.ScrubReason -eq 'fixture corruption') 'Verified scrub must surface its use and restart requirement without leaking log messages.'
} else {
$pattern=switch ($script:scrubMode) { 'download' {'Scrub download failed'}; 'bad-help' {'Could not validate.*Scrub was not launched'}; 'preexisting-worker' {'Cannot launch scrub.*worker is running'}; 'invalid-arguments' {'rejected its command line.*process 0'}; 'usage' {'rejected its command line.*process 0'}; 'background-no-worker' {'background removal did not finish verification'}; 'background' {'processes are still running'}; 'running' {'processes are still running'}; 'remaining' {'Office remains.*Leftover MSI Office'}; 'inventory-error' {'Registry unreadable'}; 'stale' {'Click-to-Run state remains'}; default {'failed or returned an unverified result'} }
$pattern=switch ($script:scrubMode) { 'download' {'Scrub download failed'}; 'bad-help' {'Could not validate.*Scrub was not launched'}; 'preexisting-worker' {'Cannot launch scrub.*worker is running'}; 'invalid-arguments' {'rejected its command line.*process 0'}; 'usage' {'rejected its command line.*process 0'}; 'background-no-worker' {'background removal did not finish verification'}; 'background' {'processes are still running'}; 'running' {'processes are still running'}; 'remaining' {'Office remains.*Leftover MSI Office'}; 'inventory-error' {'Registry unreadable'}; 'stale' {'Removal verification failed'}; default {'failed or returned an unverified result'} }
Assert-OfficeThrows { Invoke-OfficeScrubRecovery $media $workspace 'fixture corruption' } $pattern
}
Assert-OfficeTest ($script:usageCalls -eq $(if ($script:scrubMode -eq 'download') {0} else {1})) 'Probe the fresh scrubber usage exactly once, only after recovery was selected.'
@@ -1147,6 +1184,29 @@ try {
$file = Join-Path $testRoot 'not-a-directory'; Set-Content -LiteralPath $file -Value 'fixture'
Assert-OfficeThrows { Assert-OfficeWritablePath $file } 'not a directory'
}
# Regression: no product is registered, but C2R service/metadata survives.
# Exercise the real removal, readiness and installation functions together.
& {
$script:regressionInstalled=$false; $script:regressionCommands=@()
function Get-OfficeSuiteInventory { if ($script:regressionInstalled) { [pscustomobject]@{DisplayName='Click-to-Run: O365BusinessRetail'} } }
function Get-OfficeClickToRunState { [pscustomobject]@{Present=$true;SourceReferences=@('C:\Windows\SystemTemp\EmberkomOfficeDeployment\previous\ODT');WorkingConfiguration=@('orphaned-working-marker')} }
function Get-CimInstance { @() }
function Test-Path { $true }
function Get-ItemProperty { [pscustomobject]@{ProductReleaseIds='O365BusinessRetail';Platform='x64';VersionToReport='16.0.20326.20158'} }
function Invoke-OfficeScrubRecovery { throw 'Scrub must not run when no product is registered.' }
function Invoke-OfficeProcess {
param($FilePath,$Arguments,$LogPrefix)
$script:regressionCommands += $Arguments
Assert-OfficeTest ($Arguments -eq ('/configure "' + $media.Config + '"') -and (Split-Path -Leaf $LogPrefix) -eq 'office-install') 'Only the fresh installation configuration may run in the orphaned-service case.'
$script:regressionInstalled=$true
0
}
$media=[pscustomobject]@{Setup='inert-setup.exe';Config=(Join-Path $testRoot 'fresh-install.xml');Version='16.0.20326.20158'}
$options=[pscustomobject]@{OfficeArchitecture='64';ProductId='O365BusinessRetail';TargetOfficeVersion='16.0.20326.20158'}
Assert-OfficeTest ((Remove-OfficeSuite $media $testRoot) -eq 0) 'An orphaned service must skip removal even without a removal configuration.'
Assert-OfficeRemovalComplete $testRoot
Assert-OfficeTest ((Install-OfficeMedia $options $media $testRoot) -eq 0 -and $script:regressionCommands.Count -eq 1) 'The orphaned-service path must reach and verify the requested installation.'
}
# Inspect persisted state without touching the actual registry or Office service.
& {
function Test-Path { return $true }
@@ -1156,11 +1216,20 @@ try {
function Get-ItemProperty { [pscustomobject]@{WorkingConfiguration='old-guid';SourcePath='C:\Windows\SystemTemp\EmberkomOfficeDeployment\old\ODT';Platform='x64'} }
$state = Get-OfficeClickToRunState
Assert-OfficeTest ($state.Present -and $state.WorkingConfiguration[0] -eq 'old-guid' -and $state.SourceReferences.Count -eq 1) 'Interrupted Click-to-Run configuration must be detected without installed products.'
Assert-OfficeThrows { Assert-OfficeFreshInstallState } 'still retains previous deployment state.*Installation stopped.*old-guid'
function Get-CimInstance { @() }
function Get-OfficeSuiteInventory { @() }
Assert-OfficeTest (@(Assert-OfficeRemovalComplete $testRoot).Count -eq 0) 'Service, working markers and old source references alone must not block an otherwise idle installation.'
function Get-CimInstance { [pscustomobject]@{Name='setup.exe';ProcessId=123;CommandLine='setup.exe /configure remove.xml'} }
Assert-OfficeThrows { Assert-OfficeRemovalComplete $testRoot } 'workers are still running'
function Get-CimInstance { @() }
function Get-OfficeSuiteInventory { [pscustomobject]@{DisplayName='Registered C2R Office'} }
Assert-OfficeThrows { Assert-OfficeRemovalComplete $testRoot } 'products remain before replacement'
function Get-OfficeSuiteInventory { [pscustomobject]@{DisplayName='MSI Office';WindowsInstaller=1} }
Assert-OfficeTest (@(Assert-OfficeRemovalComplete $testRoot).Count -eq 0) 'Legacy MSI products remain assigned to RemoveMSI during installation.'
function Get-ItemProperty { [pscustomobject]@{Platform='x64'} }
$null = Assert-OfficeFreshInstallState
$null = Assert-OfficeRemovalComplete
function Get-ItemProperty { throw 'Registry access denied' }
Assert-OfficeThrows { Assert-OfficeFreshInstallState } 'Registry access denied'
Assert-OfficeThrows { Assert-OfficeRemovalComplete } 'Registry access denied'
}
# Execute the real deferred action with only its live download replaced.
& {
@@ -1279,7 +1348,7 @@ try {
function Test-OfficeDownloadLinks { [pscustomobject]@{StatusCode=200;Method='HEAD'} }
function Get-OfficeClickToRunState { [pscustomobject]@{Present=$false;SourceReferences=@();WorkingConfiguration=@()} }
function Clear-OfficePreviousDeploymentFiles { if ($script:mode -eq 'old-cache') { throw 'Previous artifacts are locked' }; $script:priorCleanupRuns++ }
function Assert-OfficeFreshInstallState { if ($script:mode -eq 'stale-state') { throw 'Previous Click-to-Run state remains' } }
function Assert-OfficeRemovalComplete { if ($script:mode -eq 'readiness-error') { throw 'Removal verification failed' } }
function Assert-OfficeDiskSpace { param($Workspace,[switch]$DownloadingMedia) if ($script:mode -eq 'preflight-space') { throw 'Insufficient disk space before download' }; if ($script:mode -eq 'disk-space' -and !$DownloadingMedia) { throw 'Insufficient disk space after staging' } }
function Resolve-OfficeTargetVersion { if ($script:mode -eq 'release') { throw 'Release metadata unavailable' } }
function Complete-OfficeDeploymentFiles { param($Workspace,$UserWorkspace) $script:artifactCleanupRuns++; if ($script:mode -eq 'download-cleanup') { throw 'Synthetic cleanup failure' }; if ($script:mode -eq 'cleanup-warning') { return ,@('Synthetic file in use') }; return ,@() }
@@ -1317,7 +1386,7 @@ try {
function Install-OfficeCompanionApps { param($Media,$Workspace,[bool]$InstallTeams) $script:teamsRequested=$InstallTeams; $script:events += 'install-companions'; if ($script:mode -eq 'install-companions') { throw 'companion install failure' }; [pscustomobject]@{ExitCode=$(if ($script:mode -eq 'companion-reboot') {3010} else {0}); Versions=@{NewOutlook='1'; OneDrive='1'}} }
$script:removalStillRegistered=$false
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'; DeferReboot='false'}
foreach ($script:mode in @('success','download','download-cleanup','disk-space','companions','remove-office','stale-state','identity','user','phase','install','install-companions','pending','reboot','office-reboot','companion-reboot')) {
foreach ($script:mode in @('success','download','download-cleanup','disk-space','companions','remove-office','readiness-error','identity','user','phase','install','install-companions','pending','reboot','office-reboot','companion-reboot')) {
$script:artifactCleanupRuns = 0
$script:events = @(); $errorResult = $null; $result = $null
try { $result = Invoke-OfficeDeployment $options } catch { $errorResult = $_ }
+8
View File
@@ -0,0 +1,8 @@
05:32:48 PM Information Created
Report: {
"ExecutionResult": "Failed",
"TroubleshooterName": "GH_OfficeUninstallALDA",
"Name": "Office Uninstall ALDA",
"ExecutionResultDetails": "There are no supported Office products installed.",
"DiagnosticName": "Utility-GetOfficeProducts"
}