fixed an issue with the cli args for the scrubber tool

This commit is contained in:
2026-10-14 17:43:32 -04:00
parent b07e132b3c
commit e3fe378b41
3 changed files with 203 additions and 13 deletions
+80 -8
View File
@@ -33,10 +33,21 @@ function Get-OfficeDeploymentDefinitions {
OdtDownloadPattern = 'https://download\.microsoft\.com/[^"\s<>]+/officedeploymenttool_[a-zA-Z0-9_-]+\.exe'
GetHelpUrl = 'https://aka.ms/SaRA_EnterpriseVersionFiles'
GetHelpExecutable = 'GetHelpCmd.exe'
ScrubArguments = '-S OfficeScrubScenario -AcceptEula -OfficeVersion All'
ScrubArguments = '-S OfficeScrubScenario -AcceptEula'
ScrubAllVersionsArgument = '-OfficeVersion All'
ScrubHelpArguments = '-?'
ScrubHelpPattern = '(?im)^\s*GetHelpCmd\.exe\s+-S\s+OfficeScrubScenario\s+-AcceptEula(?:\s|$)'
ScrubVersionSwitchPattern = '(?im)^\s*-OfficeVersion\b'
ScrubScenarioPattern = '(?m)^\s*(\d{2}):'
ScrubScenarioSuccess = @('00', '66', '68')
ScrubExitSuccess = @(0, 66, 68)
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')
HelperVersion = 'EmberkomOfficeUserCleanup-v4'
Language = 'en-us'
OfficeBuildPattern = '^16\.0\.\d+\.\d+$'
@@ -285,6 +296,13 @@ function Initialize-OfficeMedia {
$scrub = @(Get-ChildItem -LiteralPath $scrubFolder -Filter $definitions.GetHelpExecutable -File -Recurse)
if ($scrub.Count -ne 1) { throw "Microsoft download did not contain exactly one $($definitions.GetHelpExecutable)." }
Assert-OfficeMicrosoftSignature $scrub[0].FullName
# Check the downloaded executable's own syntax before any removal. Current Get Help
# rejects the documented -OfficeVersion switch and internally requests All instead.
$helpPrefix = Join-Path $Workspace 'gethelp-usage'
$helpCode = Invoke-OfficeProcess $scrub[0].FullName $definitions.ScrubHelpArguments $helpPrefix
$helpText = (Get-Content -LiteralPath "$helpPrefix.stdout.log" -Raw -ErrorAction Stop) + "`n" + (Get-Content -LiteralPath "$helpPrefix.stderr.log" -Raw -ErrorAction Stop)
$scrubArguments = Get-OfficeScrubArguments $helpCode $helpText
$null = Write-Output "Validated Get Help command: $scrubArguments. Usage logs: $helpPrefix"
# Run-Script only downloads the core file, so stage its helper explicitly.
$helper = Join-Path $Workspace 'Office-UserCleanup.ps1'
Save-OfficeDownload "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1" $helper
@@ -310,7 +328,7 @@ function Initialize-OfficeMedia {
}
$config.Configuration.Add.SetAttribute('Version', $versions[0].Name); $config.Save($configPath)
$companions = Initialize-OfficeCompanionMedia $Workspace -InstallTeams $Options.InstallTeams
[pscustomobject]@{ Setup = $setup; Scrubber = $scrub[0].FullName; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions }
[pscustomobject]@{ Setup = $setup; Scrubber = $scrub[0].FullName; ScrubArguments = $scrubArguments; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions }
}
function Get-OfficeRunningApps {
@@ -446,25 +464,79 @@ function Get-OfficeSuiteInventory {
if ($c2r.ProductReleaseIds) { [pscustomobject]@{ DisplayName = "Click-to-Run: $($c2r.ProductReleaseIds)" } }
}
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). No apps have been removed. Check gethelp-usage logs."
}
if ($HelpText -match $definitions.ScrubVersionSwitchPattern) { return "$($definitions.ScrubArguments) $($definitions.ScrubAllVersionsArgument)" }
$definitions.ScrubArguments
}
function Assert-OfficeScrubResult {
param([int]$ExitCode, [string]$Output, [object[]]$RemainingOffice)
# Microsoft's scenario output is checked separately from the process exit code.
$definitions = Get-OfficeDeploymentDefinitions
$summary = ($Output -replace '\s+', ' ').Trim()
if ($summary.Length -gt 1000) { $summary = $summary.Substring(0, 1000) + '...' }
if ($Output -match $definitions.ScrubFailurePattern) { throw "Get Help removal failed (process exit $ExitCode). $summary" }
$results = [regex]::Matches($Output, $definitions.ScrubScenarioPattern)
if (!$results.Count) { throw "Get Help returned no recognizable scenario result (process exit $ExitCode). Check scrub logs." }
$result = $results[$results.Count - 1].Groups[1].Value
if ($result -notin $definitions.ScrubScenarioSuccess -or $ExitCode -notin $definitions.ScrubExitSuccess) { throw "Get Help removal failed: scenario $result, process $ExitCode. Check scrub logs." }
if ($results.Count) {
$failed = @($results | Where-Object { $_.Groups[1].Value -notin $definitions.ScrubScenarioSuccess })
if ($failed.Count -or $ExitCode -notin $definitions.ScrubExitSuccess) { throw "Get Help removal failed: scenario $($results[$results.Count - 1].Groups[1].Value), process $ExitCode. $summary" }
} elseif ($Output -notmatch $definitions.ScrubTextSuccessPattern -or $ExitCode -ne 0) {
throw "Get Help returned no recognizable successful scenario result (process exit $ExitCode). Output: $summary. Check scrub logs."
}
if (@($RemainingOffice).Count) { throw "Office remains after cleanup: $(($RemainingOffice | ForEach-Object { $_.DisplayName }) -join '; '). Reboot/repair and rerun; installation stopped." }
}
function Get-OfficeScrubWorkers {
$definitions = Get-OfficeDeploymentDefinitions
$filter = ($definitions.ScrubWorkerNames | ForEach-Object { "Name='$_'" }) -join ' OR '
Get-CimInstance Win32_Process -Filter $filter -ErrorAction Stop | Where-Object {
# Idle service hosts can outlive an uninstall. Track clients and script workers.
$_.ProcessId -ne $PID -and
!($_.Name -eq 'msiexec.exe' -and $_.CommandLine -match '(?i)\s/(V|Embedding)\b') -and
!($_.Name -eq 'OfficeClickToRun.exe' -and $_.CommandLine -match '(?i)\s/service\b')
}
}
function Wait-OfficeScrubRemoval {
param([object[]]$ExistingWorkers)
$definitions = Get-OfficeDeploymentDefinitions
$baseline = @{}
foreach ($worker in $ExistingWorkers) { $baseline["$($worker.ProcessId)|$($worker.CreationDate)"] = $true }
$quietChecks = 0; $lastState = $null
$null = Write-Output "Get Help started background removal. Waiting up to $([int](($definitions.ScrubBackgroundCheckAttempts - 1) * $definitions.ScrubBackgroundCheckSeconds / 60)) minutes for Office removal and cleanup workers to finish."
for ($attempt = 1; $attempt -le $definitions.ScrubBackgroundCheckAttempts; $attempt++) {
$remaining = @(Get-OfficeSuiteInventory)
$workers = @(Get-OfficeScrubWorkers | Where-Object {
!$baseline.ContainsKey("$($_.ProcessId)|$($_.CreationDate)") -or $_.CommandLine -match '(?i)(OffScrub|OfficeScrub|OfficeUninstall)'
})
$state = "Office: $(($remaining.DisplayName | Sort-Object) -join '; '); cleanup workers: $(($workers | ForEach-Object { "$($_.Name) PID $($_.ProcessId)" } | Sort-Object) -join '; ')"
if ($state -ne $lastState) { $null = Write-Output $state; $lastState = $state }
if (!$remaining.Count -and !$workers.Count) { $quietChecks++ } else { $quietChecks = 0 }
# A launch acknowledgement is not completion. Require a quiet interval as well
# as empty inventory to avoid starting ODT while a detected detached worker is active.
if ($quietChecks -ge $definitions.ScrubBackgroundQuietChecks) { return }
if ($attempt -lt $definitions.ScrubBackgroundCheckAttempts) { Start-Sleep -Seconds $definitions.ScrubBackgroundCheckSeconds }
}
throw "Get Help background removal did not finish within the allowed time. $state. Installation stopped. Check scrub logs and restart before rerunning if cleanup is still active."
}
function Remove-OfficeSuite {
param($Media, [string]$Workspace)
$null = Write-Output 'Removing Office, including Visio and Project, with Microsoft Get Help.'
$prefix = Join-Path $Workspace 'office-scrub'
$code = Invoke-OfficeProcess $Media.Scrubber (Get-OfficeDeploymentDefinitions).ScrubArguments $prefix
$output = (Get-Content -LiteralPath "$prefix.stdout.log" -Raw -ErrorAction Stop) + (Get-Content -LiteralPath "$prefix.stderr.log" -Raw -ErrorAction Stop)
if (!$Media.ScrubArguments) { throw 'Get Help command syntax was not validated before removal.' }
$existingWorkers = @(Get-OfficeScrubWorkers)
$code = Invoke-OfficeProcess $Media.Scrubber $Media.ScrubArguments $prefix
$output = (Get-Content -LiteralPath "$prefix.stdout.log" -Raw -ErrorAction Stop) + "`n" + (Get-Content -LiteralPath "$prefix.stderr.log" -Raw -ErrorAction Stop)
$null = Write-Output "Get Help output ($prefix):`n$output"
Assert-OfficeScrubResult $code $output @()
$null = Wait-OfficeResult { @(Get-OfficeSuiteInventory).Count -eq 0 } 'Office removal registration'
if ($output -match (Get-OfficeDeploymentDefinitions).ScrubBackgroundPattern) { Wait-OfficeScrubRemoval $existingWorkers }
else { $null = Wait-OfficeResult { @(Get-OfficeSuiteInventory).Count -eq 0 } 'Office removal registration' }
Assert-OfficeScrubResult $code $output @(Get-OfficeSuiteInventory)
}