more fixes for scrubber

This commit is contained in:
2026-10-29 17:05:00 -04:00
parent 597524fc13
commit 0c614596f8
4 changed files with 228 additions and 28 deletions
+113 -17
View File
@@ -34,9 +34,18 @@ function Get-OfficeDeploymentDefinitions {
ManualScrubUrl = 'https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall'
GetHelpUrl = 'https://aka.ms/SaRA_EnterpriseVersionFiles'
GetHelpExecutable = 'GetHelpCmd.exe'
# The current GetHelpCmd build rejects -OfficeVersion, despite the older
# scenario documentation listing it. Use the tool's own supported example.
# Probe each fresh download's usage; add OfficeVersion only when advertised.
ScrubArguments = '-S OfficeScrubScenario -AcceptEula'
ScrubAllVersionsArgument = '-OfficeVersion All'
ScrubHelpPattern = '(?im)^\s*GetHelpCmd\.exe\s+-S\s+OfficeScrubScenario\s+-AcceptEula(?:\s|$)'
ScrubVersionSwitchPattern = '(?im)^\s*-OfficeVersion\b'
ScrubTextSuccessPattern = '(?im)^\s*Scenario completed successfully\.\s*$'
ScrubBackgroundPattern = '(?im)^\s*ExecutionResultDetails:\s*Uninstall office is running in the background\.'
ScrubFailurePattern = '(?im)^\s*(?:Error\s*:|(?:-\s*)?Uninstall Office Scenario failed\.|The scenario requires an elevated command-prompt\.)'
ScrubBackgroundCheckAttempts = 181
ScrubBackgroundCheckSeconds = 10
ScrubBackgroundQuietChecks = 7
ScrubWorkerNames = @('powershell.exe', 'pwsh.exe', 'cscript.exe', 'wscript.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'OfficeClickToRun.exe', 'setup.exe', 'integratedoffice.exe', 'GetHelpCmd.exe', 'SaRAcmd.exe')
ScrubRecoveryExitCodes = @(17002, 17004)
ScrubDiagnosticLineLimit = 20
ScrubDiagnosticLineCharacters = 2000
@@ -415,6 +424,8 @@ function Get-OfficeBlockingProcesses {
param([string]$Workspace, [object[]]$Processes)
# Be conservative even when a child installer no longer names its source folder.
foreach ($process in $Processes) {
# Windows Installer service/server hosts can remain after their clients exit.
if ($process.Name -eq 'msiexec.exe' -and $process.CommandLine -match '(?i)\s/(V|Embedding)(?:\s|$)') { continue }
if ($process.Name -in @('setup.exe', 'odt.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'GetHelpCmd.exe', 'SaRAcmd.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe')) { $process; continue }
if ($process.Name -eq 'OfficeClickToRun.exe' -and $process.CommandLine -notmatch '(?i)\s/(service|user)\s*$') { $process; continue }
if ($process.CommandLine -match '(?i)\b(OffScrub[^\s"\\/]*\.(vbs|ps1)|OfficeScrubScenario)\b') { $process; continue }
@@ -945,6 +956,94 @@ function Read-OfficeScrubOutput {
$output -join "`n"
}
function Get-OfficeScrubArguments {
param([int]$ExitCode, [string]$HelpText)
$definitions = Get-OfficeDeploymentDefinitions
if ($ExitCode -ne 0 -or $HelpText -match $definitions.ScrubFailurePattern -or $HelpText -notmatch $definitions.ScrubHelpPattern) {
throw "Could not validate the downloaded Get Help command syntax (exit $ExitCode). Scrub was not launched. Check gethelp-usage logs."
}
if ($HelpText -match $definitions.ScrubVersionSwitchPattern) { return "$($definitions.ScrubArguments) $($definitions.ScrubAllVersionsArgument)" }
return $definitions.ScrubArguments
}
function Get-OfficeScrubWorkers {
$definitions = Get-OfficeDeploymentDefinitions
$filter = ($definitions.ScrubWorkerNames | ForEach-Object { "Name='$_'" }) -join ' OR '
Get-CimInstance Win32_Process -Filter $filter -ErrorAction Stop | Where-Object {
$_.ProcessId -ne $PID -and
!($_.Name -eq 'msiexec.exe' -and $_.CommandLine -match '(?i)\s/(V|Embedding)(?:\s|$)') -and
!($_.Name -eq 'OfficeClickToRun.exe' -and $_.CommandLine -match '(?i)\s/(service|user)\s*$')
}
}
function Open-OfficeScrubWorkerHandle {
param($Worker)
# Hold a real handle before the process exits. Looking up a departed PID later
# loses its exit code and can accidentally refer to a reused PID.
$process = $null
try {
$process = [Diagnostics.Process]::GetProcessById([int]$Worker.ProcessId)
$null = $process.Handle
if (!$Worker.CreationDate -or [Math]::Abs(($process.StartTime.ToUniversalTime() - ([datetime]$Worker.CreationDate).ToUniversalTime()).TotalMilliseconds) -gt 1) { throw 'Process identity changed.' }
return $process
} catch {
if ($process) { $process.Dispose() }
throw "Could not monitor scrub worker PID $($Worker.ProcessId): $($_.Exception.Message) Installation stopped; worker disappearance is not proof of successful removal."
}
}
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 "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++) {
$workers = @(Get-OfficeScrubWorkers | Where-Object {
!$baseline.ContainsKey("$($_.ProcessId)|$(([datetime]$_.CreationDate).ToUniversalTime().Ticks)") -or $_.CommandLine -match '(?i)(OffScrub|OfficeScrub|OfficeUninstall|GetHelpElevated)'
})
foreach ($worker in $workers) {
# Track a completion code for identified Microsoft script workers.
# Newly started unrelated consoles still delay the quiet interval,
# as in the previous implementation, but cannot prove scrub ran.
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 }
$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) {
if ($watch.Checked) { continue }
if (!$watch.Process.HasExited) { $liveHandles++; continue }
$exitCode = $watch.Process.ExitCode
if ($null -eq $exitCode -or $exitCode -notin @(0, 3010)) { throw "Scrub worker PID $($watch.Id) exited unsuccessfully (exit $exitCode); it may have failed or been closed. Installation stopped." }
$watch.Checked = $true
$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"
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 ($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."
} finally {
foreach ($watch in $handles.Values) { $watch.Process.Dispose() }
}
}
function Invoke-OfficeScrubRecovery {
param($Media, [string]$Workspace, [string]$Reason)
if ($Media.ScrubAttempted) { throw 'Office scrub recovery was already attempted. Installation stopped; no repeated scrub or install loop will run.' }
@@ -953,28 +1052,25 @@ function Invoke-OfficeScrubRecovery {
$null = Write-Output "Office scrub recovery selected: $Reason"
$null = Write-Output 'Running one Microsoft Get Help OfficeScrubScenario attempt for detected Office installations. All Office registrations must be gone before replacement installation. Get Help may display a child window despite the hidden launch.'
$scrubber = Initialize-OfficeScrubMedia $Workspace
$helpPrefix = Join-Path $Workspace 'gethelp-usage'
$helpCode = Invoke-OfficeProcess $scrubber '-?' $helpPrefix
$arguments = Get-OfficeScrubArguments $helpCode (Read-OfficeScrubOutput $helpPrefix)
$null = Write-Output "Validated Get Help command: $arguments"
$prefix = Join-Path $Workspace 'office-scrub'
$code = Invoke-OfficeProcess $scrubber (Get-OfficeDeploymentDefinitions).ScrubArguments $prefix
$existingWorkers = @(Get-OfficeScrubWorkers)
$blocking = @(Get-OfficeBlockingProcesses $Workspace $existingWorkers)
if ($blocking.Count) { throw "Cannot launch scrub while another installation/removal worker is running: $(($blocking | ForEach-Object { "$($_.Name) PID $($_.ProcessId)" }) -join '; '). Installation stopped to avoid overlapping cleanup." }
$code = Invoke-OfficeProcess $scrubber $arguments $prefix
$output = Read-OfficeScrubOutput $prefix
if ($output -match '(?im)^\s*(Error:\s*)?Invalid command line arguments\b|^\s*Usage:\s*GetHelpCmd\.exe\b') {
throw "Get Help rejected its command line and printed usage (process $code). No scrub success was reported. Arguments: $((Get-OfficeDeploymentDefinitions).ScrubArguments). See Get Help stdout/stderr details in the management log and $prefix.stdout.log."
}
if ($output -match '(?im)^\s*ExecutionResultDetails:\s*Uninstall office is running in the background\.') {
# This is a launch acknowledgement, not an uninstall result. The observed
# GetHelpElevated Run.ps1 waits in Console.ReadKey in finally after BOTH
# success and failure. Neither launcher exit 0 nor worker lifetime proves
# removal, and a missing product registration can predate a corrupt scrub.
$workers = @(Get-OfficeBlockingProcesses $Workspace @(Get-CimInstance Win32_Process -ErrorAction Stop))
foreach ($worker in $workers) {
$null = Write-Output "Get Help background worker: $($worker.Name), PID $($worker.ProcessId), created $($worker.CreationDate). Command: $($worker.CommandLine)"
}
$workerSummary = if ($workers.Count) { ($workers | ForEach-Object { "$($_.Name) (PID $($_.ProcessId))" }) -join '; ' } else { 'none observed; absence does not establish success' }
throw "Get Help background removal requires attended verification (launcher exit $code; workers: $workerSummary). Get Help acknowledged launching removal, not its completion. Its GetHelpElevated Run.ps1 can wait at 'Press any key to exit' after success OR failure. Check the worker console/final diagnostic report, complete or dismiss it, and verify removal before rerunning. Installation stopped; active workers block media cleanup and new deployment. See $prefix.stdout.log."
throw "Get Help rejected its command line and printed usage (process $code). No scrub success was reported. Arguments: $arguments. See Get Help stdout/stderr details in the management log and $prefix.stdout.log."
}
$definitions = Get-OfficeDeploymentDefinitions
$results = @([regex]::Matches($output, '(?m)^\s*(\d{2}):') | ForEach-Object { $_.Groups[1].Value })
$null = Write-Output "Get Help scrub result: process $code; scenario results $($results -join ', '). Logs: $prefix"
# 66/68 mean Office was not found, not a verified repair of damaged state.
if ($code -notin @(0, 3010) -or !$results.Count -or @($results | Where-Object { $_ -ne '00' }).Count) { throw "Get Help scrub failed or returned an unverified result (process $code; scenarios $($results -join ', ')). Installation stopped. See $prefix.stdout.log and $prefix.stderr.log." }
if ($code -notin @(0, 3010) -or $output -match $definitions.ScrubFailurePattern -or @($results | Where-Object { $_ -ne '00' }).Count -or (!$results.Count -and $output -notmatch $definitions.ScrubTextSuccessPattern)) { throw "Get Help scrub failed or returned an unverified result (process $code; scenarios $($results -join ', ')). Installation stopped. See $prefix.stdout.log and $prefix.stderr.log." }
if ($output -match $definitions.ScrubBackgroundPattern) { Wait-OfficeScrubRemoval $existingWorkers }
$idle = Wait-OfficeResult { !(Test-OfficeStagingInUse $Workspace @(Get-CimInstance Win32_Process -ErrorAction Stop)) } 'Office scrub child processes to finish'
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'