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
+65 -34
View File
@@ -846,8 +846,8 @@ function Get-OfficeSuiteInventory {
}
function Get-OfficeClickToRunState {
# Finished-product inventory misses interrupted installations. Read servicing
# state as evidence only; ODT, not registry deletion, must remove the old setup.
# Servicing metadata is diagnostic evidence, not installed-product inventory.
# A service can survive removal, and successful installs retain source URLs.
$root = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun'
$present = Test-Path -LiteralPath $root -ErrorAction Stop
$sources = @(); $working = @()
@@ -869,18 +869,14 @@ function Get-OfficeClickToRunState {
[pscustomobject]@{ Present=($present -or $null -ne $service); SourceReferences=$sources; WorkingConfiguration=$working }
}
function Test-OfficeFreshInstallState {
[bool](Wait-OfficeResult {
$state = Get-OfficeClickToRunState
!$state.SourceReferences.Count -and !$state.WorkingConfiguration.Count
} 'removal of previous Click-to-Run working configuration and deployment source references')
}
function Assert-OfficeFreshInstallState {
if (!(Test-OfficeFreshInstallState)) {
$state = Get-OfficeClickToRunState
throw "Click-to-Run still retains previous deployment state after ODT removal. Installation stopped to prevent reuse of old content. Working configuration: $($state.WorkingConfiguration -join ', '). Source references: $($state.SourceReferences -join '; '). Arrange an attended Office repair/scrub: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)"
}
function Assert-OfficeRemovalComplete {
param([string]$Workspace)
$idle = Wait-OfficeResult { !(Test-OfficeStagingInUse $Workspace @(Get-CimInstance Win32_Process -ErrorAction Stop)) } 'Office installation/removal workers to finish before replacement'
if (!$idle) { throw 'Office installation/removal workers are still running. Installation stopped to avoid overlapping operations.' }
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 })
if ($remaining.Count) { throw "Click-to-Run products remain before replacement: $($remaining.DisplayName -join '; '). Installation stopped." }
$state = Get-OfficeClickToRunState
$null = Write-Output "Office removal verified: no registered Click-to-Run products or active installer workers. Diagnostic metadata: $($state.SourceReferences.Count) staging references; working configuration: $($state.WorkingConfiguration -join ', '). Metadata alone does not require removal; ODT will configure this run's fresh media."
}
function Get-OfficeRemovalCorruptionEvidence {
@@ -992,12 +988,46 @@ function Open-OfficeScrubWorkerHandle {
}
}
function Get-OfficeScrubReportRoots {
param($Worker)
try {
$owner = Invoke-CimMethod -InputObject $Worker -MethodName GetOwnerSid -ErrorAction Stop
if ($owner.ReturnValue -ne 0 -or !$owner.Sid) { throw 'Worker owner SID is unavailable.' }
if ($owner.Sid -eq 'S-1-5-18') {
"$env:WINDIR\System32\config\systemprofile\AppData\Local\DAFs"
"$env:WINDIR\SysWOW64\config\systemprofile\AppData\Local\DAFs"
} else {
$profile = Get-ItemPropertyValue -LiteralPath "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$($owner.Sid)" -Name ProfileImagePath -ErrorAction Stop
Join-Path ([Environment]::ExpandEnvironmentVariables($profile)) 'AppData\Local\DAFs'
}
} catch { $null = Write-Output "Could not locate diagnostic reports for scrub worker PID $($Worker.ProcessId): $($_.Exception.Message). Process and product verification remain required." }
}
function Read-OfficeScrubWorkerReport {
param($Worker, [string[]]$Roots)
foreach ($root in $Roots) {
try {
if (!(Test-Path -LiteralPath $root -ErrorAction Stop)) { continue }
foreach ($file in @(Get-ChildItem -LiteralPath $root -Filter 'cse.amplify.diagaction.gethelp.officeuninstallalda_*.log' -File -ErrorAction Stop)) {
# Only fresh reports in this worker's account. Never apply an older
# scrub's failure to the current run or use a report to kill a worker.
if ($file.CreationTimeUtc -lt ([datetime]$Worker.CreationDate).ToUniversalTime() -or $file.LastWriteTimeUtc -lt ([datetime]$Worker.CreationDate).ToUniversalTime() -or $file.Length -gt 1MB) { continue }
$text = Get-Content -LiteralPath $file.FullName -Raw -ErrorAction Stop
if ($text -notmatch '(?s)\bReport:\s*(\{.*\})\s*$') { continue }
try { $report = $Matches[1] | ConvertFrom-Json -ErrorAction Stop } catch { continue } # It may still be being written.
if ($report.TroubleshooterName -ne 'GH_OfficeUninstallALDA' -or !$report.ExecutionResult) { continue }
[pscustomobject]@{ Path=$file.FullName; Result=$report.ExecutionResult; Detail=$report.ExecutionResultDetails }
}
} catch { $null = Write-Output "Could not read scrub reports in ${root}: $($_.Exception.Message)." }
}
}
function Wait-OfficeScrubRemoval {
param([object[]]$ExistingWorkers)
$definitions = Get-OfficeDeploymentDefinitions
$baseline = @{}; $handles = @{}; $quietChecks = 0; $lastState = $null; $observedWorker = $false
foreach ($worker in $ExistingWorkers) { $baseline["$($worker.ProcessId)|$(([datetime]$worker.CreationDate).ToUniversalTime().Ticks)"] = $true }
$null = Write-Output "Get Help started background removal. Waiting up to $([int](($definitions.ScrubBackgroundCheckAttempts - 1) * $definitions.ScrubBackgroundCheckSeconds / 60)) minutes for workers, Office registrations and previous deployment state to clear, followed by a $([int](($definitions.ScrubBackgroundQuietChecks - 1) * $definitions.ScrubBackgroundCheckSeconds))-second quiet interval."
$null = Write-Output "Get Help started background removal. Waiting up to $([int](($definitions.ScrubBackgroundCheckAttempts - 1) * $definitions.ScrubBackgroundCheckSeconds / 60)) minutes for workers and Office registrations to clear, followed by a $([int](($definitions.ScrubBackgroundQuietChecks - 1) * $definitions.ScrubBackgroundCheckSeconds))-second quiet interval."
$null = Write-Output "Leave the Microsoft cleanup window open until it reports completion. If it says 'Press any key to exit', dismiss that completed prompt to let verification continue. Closing it during removal can fail deployment."
try {
for ($attempt = 1; $attempt -le $definitions.ScrubBackgroundCheckAttempts; $attempt++) {
@@ -1011,13 +1041,16 @@ function Wait-OfficeScrubRemoval {
if ($worker.CommandLine -notmatch '(?i)(OffScrub|OfficeScrub|OfficeUninstall|GetHelpElevated)') { continue }
$identity = "$($worker.ProcessId)|$(([datetime]$worker.CreationDate).ToUniversalTime().Ticks)"
if (!$handles.ContainsKey($identity)) {
$handles[$identity] = [pscustomobject]@{ Process=(Open-OfficeScrubWorkerHandle $worker); Checked=$false; Id=$worker.ProcessId }
$handles[$identity] = [pscustomobject]@{ Process=(Open-OfficeScrubWorkerHandle $worker); Checked=$false; Id=$worker.ProcessId; Worker=$worker; ReportRoots=@(Get-OfficeScrubReportRoots $worker) }
$observedWorker = $true
$null = Write-Output "Monitoring scrub worker $($worker.Name), PID $($worker.ProcessId), created $($worker.CreationDate). Command: $($worker.CommandLine)"
}
}
$liveHandles = 0
foreach ($watch in $handles.Values) {
foreach ($report in @(Read-OfficeScrubWorkerReport $watch.Worker $watch.ReportRoots)) {
if ($report.Result -eq 'Failed') { throw "Get Help worker reported failure: $($report.Detail) Report: $($report.Path). Installation stopped. Its console may now be waiting at the final keypress prompt; that process lifetime is not ongoing cleanup." }
}
if ($watch.Checked) { continue }
if (!$watch.Process.HasExited) { $liveHandles++; continue }
$exitCode = $watch.Process.ExitCode
@@ -1026,19 +1059,13 @@ function Wait-OfficeScrubRemoval {
$null = Write-Output "Scrub worker PID $($watch.Id) exited $exitCode. Removal still requires independent verification."
}
$remaining = @(Get-OfficeSuiteInventory)
$fresh = $false
# Avoid racing registry teardown while a known cleanup worker is active.
if (!$workers.Count -and !$liveHandles) {
$state = Get-OfficeClickToRunState
$fresh = !$state.SourceReferences.Count -and !$state.WorkingConfiguration.Count
}
$status = "Office: $(($remaining.DisplayName | Sort-Object) -join '; '); workers: $(($workers | ForEach-Object { "$($_.Name) PID $($_.ProcessId)" } | Sort-Object) -join '; '); live monitored workers: $liveHandles; previous deployment state cleared: $fresh; observed scrub worker: $observedWorker"
$status = "Office registrations remaining: $($remaining.Count) [$(($remaining.DisplayName | Sort-Object) -join '; ')]; workers: $(($workers | ForEach-Object { "$($_.Name) PID $($_.ProcessId)" } | Sort-Object) -join '; '); live monitored workers: $liveHandles; observed scrub worker: $observedWorker"
if ($status -ne $lastState -or $attempt % 6 -eq 0) { $null = Write-Output $status; $lastState = $status }
if ($observedWorker -and !$remaining.Count -and !$workers.Count -and !$liveHandles -and $fresh) { $quietChecks++ } else { $quietChecks = 0 }
if ($observedWorker -and !$remaining.Count -and !$workers.Count -and !$liveHandles) { $quietChecks++ } else { $quietChecks = 0 }
if ($quietChecks -ge $definitions.ScrubBackgroundQuietChecks) { return }
if ($attempt -lt $definitions.ScrubBackgroundCheckAttempts) { Start-Sleep -Seconds $definitions.ScrubBackgroundCheckSeconds }
}
throw "Get Help background removal did not finish verification within the allowed time. $status. Installation stopped. Finish any completed keypress prompt; inspect scrub logs if removal failed or no worker was observed."
throw "Get Help background removal did not finish verification within the allowed time. $status. Installation has not started and this deployment will not resume automatically. A live worker alone cannot distinguish active removal from the final keypress prompt, which Microsoft displays after success OR failure. Inspect its final console output or diagnostic report before dismissing a completed prompt."
} finally {
foreach ($watch in $handles.Values) { $watch.Process.Dispose() }
}
@@ -1075,7 +1102,7 @@ function Invoke-OfficeScrubRecovery {
if (!$idle) { throw 'Office scrub processes are still running. Installation stopped to avoid concurrent removal and installation.' }
$removed = Wait-OfficeResult { @(Get-OfficeSuiteInventory).Count -eq 0 } 'all Office registrations to disappear after Get Help scrub'
if (!$removed) { throw "Office remains after Get Help scrub: $((Get-OfficeSuiteInventory).DisplayName -join '; '). Installation stopped." }
Assert-OfficeFreshInstallState
Assert-OfficeRemovalComplete $Workspace
$null = Write-Output 'Office scrub recovery verified. Reporting restart required; DeferReboot controls whether installation can finish before that restart.'
return 3010
}
@@ -1083,17 +1110,16 @@ function Invoke-OfficeScrubRecovery {
function Remove-OfficeSuite {
param($Media, [string]$Workspace)
# ODT is the normal path. A single Get Help scrub is reserved for evidence of
# broken removal or residual state, before replacement installation begins.
# broken product removal, before replacement installation begins.
$existing = @(Get-OfficeSuiteInventory)
$msi = @($existing | Where-Object { $_.WindowsInstaller -eq 1 })
if ($msi.Count) { $null = Write-Output "MSI Office will be removed by ODT RemoveMSI before it installs the replacement suite: $($msi.DisplayName -join '; ')." }
$state = Get-OfficeClickToRunState
if (!@($existing | Where-Object { $_.WindowsInstaller -ne 1 }).Count -and !$state.Present) {
$null = Write-Output 'No Click-to-Run products, service or servicing state detected; skipping the separate ODT removal pass.'
if (!@($existing | Where-Object { $_.WindowsInstaller -ne 1 }).Count) {
$null = Write-Output 'No registered Click-to-Run products detected; skipping ODT removal and scrub. A remaining ClickToRunSvc or servicing key is not an installed Office product. MSI products remain assigned to RemoveMSI during installation.'
return 0
}
if (!$Media.RemovalConfig -or !(Test-Path -LiteralPath $Media.RemovalConfig -PathType Leaf)) { throw 'The staged silent Office removal configuration is missing.' }
$null = Write-Output 'Silently removing Click-to-Run Office, including incomplete deployments, Visio and Project, with ODT.'
$null = Write-Output "Silently removing registered Click-to-Run products with ODT: $(($existing | Where-Object { $_.WindowsInstaller -ne 1 }).DisplayName -join '; ')."
$startedUtc = [DateTime]::UtcNow
$code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.RemovalConfig)`"" (Join-Path $Workspace 'office-remove')
if ($code -notin @(0, 3010)) {
@@ -1101,6 +1127,12 @@ function Remove-OfficeSuite {
$evidence = Get-OfficeRemovalCorruptionEvidence -SinceUtc $startedUtc
if ($evidence) {
$null = Write-Output "Office scrub trigger evidence: $($evidence.Path) : $($evidence.Detail)"
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 })
if (!$remaining.Count) {
Assert-OfficeRemovalComplete $Workspace
$null = Write-Output "ODT removal exited $code, but no Click-to-Run products or active workers remain. Skipping a scrub with no product to remove; reporting restart required before continuing according to DeferReboot."
return 3010
}
return Invoke-OfficeScrubRecovery $Media $Workspace "ODT removal exit $code with a current REMOVEINSTALLATION InvalidDirectory error."
}
}
@@ -1112,7 +1144,6 @@ function Remove-OfficeSuite {
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 })
return Invoke-OfficeScrubRecovery $Media $Workspace "Office remains after successful ODT removal: $($remaining.DisplayName -join '; ')."
}
if (!(Test-OfficeFreshInstallState)) { return Invoke-OfficeScrubRecovery $Media $Workspace 'Previous Click-to-Run working configuration or deployment source references remain after successful ODT removal.' }
return 0
}
@@ -1440,7 +1471,7 @@ function Invoke-OfficeDeployment {
UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams; OfficeRemovalMethod='SilentODT'; DeferReboot=$Options.DeferReboot
Workspace=$null; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps; MediaDownloaded=$false
WritablePaths=$writablePaths; DownloadChecks=$downloadChecks; ClickToRunState=$state; OfficeFeatureRelease=$Options.OfficeFeatureRelease; MetadataResolved=$false
ScrubRecoveryPolicy='One Get Help scrub for confirmed removal corruption or residual state after successful ODT removal; deployment only.'
ScrubRecoveryPolicy='One Get Help scrub for failed removal with registered Click-to-Run products remaining; deployment only. Servicing metadata alone does not trigger removal.'
NextStep='Set ValidateBeforeChanges=false to download, verify, deploy, and clean up installation media. Prerequisites are checked again.'
}
}
@@ -1466,7 +1497,7 @@ function Invoke-OfficeDeployment {
$receipt = [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @(); ArtifactCleanupPending=$false; ScrubRecoveryAttempted=[bool]$media.ScrubAttempted; ScrubRecoveryReason=$media.ScrubReason }
return $receipt
}
Assert-OfficeFreshInstallState
Assert-OfficeRemovalComplete $workspace
foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile }
$userWorkspace = $workspace
if ($profiles.Count) { $userWorkspace = New-OfficeUserWorkspace $media $workspace }