From a8b8429b5831621f99d7c91e0d6c1dec0bc95b4b Mon Sep 17 00:00:00 2001 From: ek-dyoder Date: Thu, 29 Oct 2026 15:24:01 -0400 Subject: [PATCH] fix scrubber call --- Install-MicrosoftOffice365.ps1 | 40 ++++++++++++++++++++-- docs/Office365-Deployment.md | 6 ++-- tests/Install-MicrosoftOffice365.Tests.ps1 | 27 +++++++++++++-- 3 files changed, 65 insertions(+), 8 deletions(-) diff --git a/Install-MicrosoftOffice365.ps1 b/Install-MicrosoftOffice365.ps1 index 03ef798..76711fd 100644 --- a/Install-MicrosoftOffice365.ps1 +++ b/Install-MicrosoftOffice365.ps1 @@ -34,8 +34,12 @@ 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' - ScrubArguments = '-S OfficeScrubScenario -AcceptEula -OfficeVersion All' + # The current GetHelpCmd build rejects -OfficeVersion, despite the older + # scenario documentation listing it. Use the tool's own supported example. + ScrubArguments = '-S OfficeScrubScenario -AcceptEula' ScrubRecoveryExitCodes = @(17002, 17004) + ScrubDiagnosticLineLimit = 20 + ScrubDiagnosticLineCharacters = 2000 HelperVersion = 'EmberkomOfficeUserCleanup-v5' Language = 'en-us' OfficeBuildPattern = '^16\.0\.\d+\.\d+$' @@ -906,17 +910,47 @@ function Initialize-OfficeScrubMedia { $executables[0].FullName } +function Read-OfficeScrubOutput { + param([string]$LogPrefix) + $definitions = Get-OfficeDeploymentDefinitions + $output = @() + foreach ($stream in @('stdout', 'stderr')) { + $path = "$LogPrefix.$stream.log" + $file = Get-Item -LiteralPath $path -ErrorAction Stop + [string]$content = Get-Content -LiteralPath $path -Raw -ErrorAction Stop + $null = Write-Output "Get Help ${stream}: $($file.Length) bytes in $path" + if ([string]::IsNullOrWhiteSpace($content)) { $null = Write-Output "Get Help ${stream}: no text captured." } + else { + $lines = @($content -split '\r?\n' | Where-Object { ![string]::IsNullOrWhiteSpace($_) }) + if ($lines.Count -gt $definitions.ScrubDiagnosticLineLimit) { + # Usage failures put the reason first and examples last. Preserve both. + $headCount = [int][Math]::Floor($definitions.ScrubDiagnosticLineLimit / 2) + $lines = @($lines | Select-Object -First $headCount) + @('[middle output omitted; see full stream log]') + @($lines | Select-Object -Last ($definitions.ScrubDiagnosticLineLimit - $headCount)) + } + foreach ($line in $lines) { + if ($line.Length -gt $definitions.ScrubDiagnosticLineCharacters) { $line = $line.Substring(0, $definitions.ScrubDiagnosticLineCharacters) + ' [truncated; see full stream log]' } + $null = Write-Output "Get Help ${stream} detail: $line" + } + } + $output += $content + } + $output -join "`n" +} + 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.' } $Media | Add-Member -NotePropertyName ScrubAttempted -NotePropertyValue $true -Force $Media | Add-Member -NotePropertyName ScrubReason -NotePropertyValue $Reason -Force $null = Write-Output "Office scrub recovery selected: $Reason" - $null = Write-Output 'Running one Microsoft Get Help OfficeScrubScenario attempt. It removes all Office versions, including Visio/Project. Get Help may display a child window despite the hidden launch.' + $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 $prefix = Join-Path $Workspace 'office-scrub' $code = Invoke-OfficeProcess $scrubber (Get-OfficeDeploymentDefinitions).ScrubArguments $prefix - $output = (Get-Content -LiteralPath "$prefix.stdout.log" -Raw -ErrorAction Stop) + "`n" + (Get-Content -LiteralPath "$prefix.stderr.log" -Raw -ErrorAction Stop) + $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." + } $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. diff --git a/docs/Office365-Deployment.md b/docs/Office365-Deployment.md index 500eb47..03a7641 100644 --- a/docs/Office365-Deployment.md +++ b/docs/Office365-Deployment.md @@ -109,7 +109,9 @@ Automatic recovery is limited to **one Get Help Office scrub per deployment**, b - ODT exits zero, but non-MSI Office registrations remain after the bounded verification wait. - ODT exits zero and product removal is verified, but previous Click-to-Run working configuration or deployment source references remain after their verification wait. -Recovery downloads a fresh package from Microsoft's evergreen Get Help link into this run's workspace, validates ZIP paths and the extracted executable's Microsoft signature, and invokes `GetHelpCmd.exe -S OfficeScrubScenario -AcceptEula -OfficeVersion All`. This removes all Office versions, including MSI Office, Visio and Project. It does not retry the scrub. Logs include the trigger, native evidence where available, process result, and scenario result. Get Help process exit `0` or `3010` **and** scenario result `00` are required; missing results, failures, or the `66`/`68` not-found results stop installation. It then verifies that scrub workers have finished, all detected Office registrations are gone, and previous Click-to-Run working/source state is cleared. Read/verification failures stop deployment. `office-scrub.stdout.log` and `.stderr.log` survive cleanup; the downloaded ZIP and extracted non-log files are removed by the same `finally` cleanup as other media. +Recovery downloads a fresh package from Microsoft's evergreen Get Help link into this run's workspace, validates ZIP paths and the extracted executable's Microsoft signature, and invokes `GetHelpCmd.exe -S OfficeScrubScenario -AcceptEula`. The build observed on October 29, 2026 rejects the previously documented `-OfficeVersion All` option with `Error: Invalid command line arguments`, prints usage, and exits zero. The script therefore uses the example advertised by the tool itself and explicitly rejects argument/usage errors even with exit zero. The scenario targets detected Office installations; verification still requires all Office registrations, including MSI Office, Visio and Project, to be gone. It does not retry the scrub. + +Logs include the trigger, native evidence where available, process result, and scenario result. The management log also records stdout/stderr byte counts and bounded excerpts from both the beginning and end, preserving startup errors and final results. The original stream logs retain full output. Get Help process exit `0` or `3010` **and** scenario result `00` are required; missing results, failures, or the `66`/`68` not-found results stop installation. It then verifies that scrub workers have finished, all detected Office registrations are gone, and previous Click-to-Run working/source state is cleared. Read/verification failures stop deployment. `office-scrub.stdout.log` and `.stderr.log` survive cleanup; the downloaded ZIP and extracted non-log files are removed by the same `finally` cleanup as other media. A verified scrub reports `3010` because Microsoft recommends a restart to finish cleanup. With `DeferReboot=true`, installation can continue after verification and the final receipt preserves the restart requirement. With `false`, the script returns `RestartRequiredBeforeInstall`. Returned Office-removal/install receipts include `ScrubRecoveryAttempted` and `ScrubRecoveryReason`. No automatic reboot or resume task is created. See [Microsoft's Office scrub guidance](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall). @@ -183,7 +185,7 @@ The installer verifies the selected Office product, bitness, and downloaded vers ## Verification -Run `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\Install-MicrosoftOffice365.Tests.ps1` for offline checks in Windows PowerShell 5.1. Coverage includes HEAD-only assessment and status failures, temporary write probes, no metadata/staging/housekeeping during assessment, prior-run cleanup with nested-log preservation, active-process/task and locked-file protection, live user-helper execution, orphaned Click-to-Run removal and stale-state rejection. Recovery checks cover the observed InvalidDirectory error, exclusion of stale/unrelated evidence, ZIP containment, signature failures, one-attempt enforcement, ambiguous/failed/not-found scrub results, surviving workers, all-product removal verification, log preservation and both restart policies. Existing checks cover strings through the real shim/Tools loader, exit-code propagation, native-host relaunch, deployment order, companion verification, retries and identity cleanup boundaries. Tests mock downloads and disruptive actions; they do not run Microsoft installers, change actual registry state, or clear credentials. +Run `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\Install-MicrosoftOffice365.Tests.ps1` for offline checks in Windows PowerShell 5.1. Coverage includes HEAD-only assessment and status failures, temporary write probes, no metadata/staging/housekeeping during assessment, prior-run cleanup with nested-log preservation, active-process/task and locked-file protection, live user-helper execution, orphaned Click-to-Run removal and stale-state rejection. Recovery checks cover the observed InvalidDirectory error, exclusion of stale/unrelated evidence, ZIP containment, signature failures, one-attempt enforcement, ambiguous/failed/not-found scrub results, zero-exit argument/usage errors, bounded stream excerpts without changing parser input, surviving workers, all-product removal verification, log preservation and both restart policies. Existing checks cover strings through the real shim/Tools loader, exit-code propagation, native-host relaunch, deployment order, companion verification, retries and identity cleanup boundaries. Tests mock downloads and disruptive actions; they do not run Microsoft installers, change actual registry state, or clear credentials. `Run-Script` is unchanged. Its existing local execution can read the Syncro variables from the enclosing caller scope. The Office workload validates those values and reports its own result and exit code. The shim only sets TLS, dot-sources `Tools.ps1`, and invokes the workload. Existing `Run-Script` bootstrap failure behavior also remains unchanged. diff --git a/tests/Install-MicrosoftOffice365.Tests.ps1 b/tests/Install-MicrosoftOffice365.Tests.ps1 index a99805f..ee732b5 100644 --- a/tests/Install-MicrosoftOffice365.Tests.ps1 +++ b/tests/Install-MicrosoftOffice365.Tests.ps1 @@ -899,6 +899,25 @@ try { else { Assert-OfficeThrows { Initialize-OfficeScrubMedia $workspace } 'exactly one GetHelpCmd.exe' } } } + # Scrub console details must reach the management log even when no recognizable + # scenario code is emitted; excerpts are bounded without altering parser input. + & { + $prefix=Join-Path $testRoot 'scrub-output' + $stdout="Tool startup message without scenario code`n" + (('x' * 2100) + "`n") + ((1..25 | ForEach-Object { "progress $_" }) -join "`n") + $stderr='A diagnostic from stderr' + [IO.File]::WriteAllText("$prefix.stdout.log", $stdout) + [IO.File]::WriteAllText("$prefix.stderr.log", $stderr) + $output=@(Read-OfficeScrubOutput $prefix) + Assert-OfficeTest ($output.Count -eq 1 -and $output[0] -ceq ($stdout + "`n" + $stderr)) 'Diagnostic excerpts must not change the complete scrub output used for result parsing.' + $log=Get-Content -LiteralPath $Global:LogFile -Raw + Assert-OfficeTest ($log.Contains('Get Help stderr detail: A diagnostic from stderr') -and $log.Contains('Get Help stdout: ')) 'Both stream sizes and captured text must reach the main management log.' + Assert-OfficeTest ($log.Contains('Get Help stdout detail: Tool startup message without scenario code') -and $log.Contains('Get Help stdout detail: progress 25') -and !$log.Contains('Get Help stdout detail: progress 14' + [Environment]::NewLine) -and $log.Contains('[middle output omitted; see full stream log]')) 'Bounded scrub excerpts must retain initial failures and final results.' + [IO.File]::WriteAllText("$prefix.stdout.log", 'x' * 2100) + [IO.File]::WriteAllText("$prefix.stderr.log", '') + $null=Read-OfficeScrubOutput $prefix + $log=Get-Content -LiteralPath $Global:LogFile -Raw + Assert-OfficeTest ($log.Contains('[truncated; see full stream log]') -and $log.Contains('Get Help stderr: no text captured.')) 'Oversized lines and empty streams must be explicit in the management log.' + } # A scrub requires both a successful scenario/process result and independently # verified removal. Every attempt is bounded to one and cleanup retains its logs. & { @@ -912,7 +931,7 @@ try { function Invoke-OfficeProcess { param($FilePath,$Arguments,$LogPrefix) $script:scrubLaunches++ - Assert-OfficeTest ($Arguments -eq '-S OfficeScrubScenario -AcceptEula -OfficeVersion All' -and (Split-Path -Leaf $LogPrefix) -eq 'office-scrub') 'Scrub must use documented unattended arguments with separate logs.' + Assert-OfficeTest ($Arguments -eq '-S OfficeScrubScenario -AcceptEula' -and (Split-Path -Leaf $LogPrefix) -eq 'office-scrub') 'Scrub must use the current tool-supported arguments, omitting the rejected OfficeVersion option.' Set-Content -LiteralPath "$LogPrefix.stdout.log" -Value $script:scrubOutput Set-Content -LiteralPath "$LogPrefix.stderr.log" -Value '' $script:scrubExit @@ -923,7 +942,7 @@ try { if ($script:scrubMode -eq 'inventory-error') { throw 'Registry unreadable' } } function Assert-OfficeFreshInstallState { if ($script:scrubMode -eq 'stale') { throw 'Previous Click-to-Run state remains' } } - foreach ($script:scrubMode in @('success','restart','download','failure','not-found-66','not-found-68','empty','contradictory','bad-exit','running','remaining','inventory-error','stale')) { + foreach ($script:scrubMode in @('success','restart','download','failure','not-found-66','not-found-68','empty','invalid-arguments','usage','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.' switch ($script:scrubMode) { @@ -932,6 +951,8 @@ try { 'not-found-66' { $script:scrubOutput='66: We could not find the specified Office version.'; $script:scrubExit=66 } 'not-found-68' { $script:scrubOutput='68: We could not find any Office version.' } 'empty' { $script:scrubOutput='' } + 'invalid-arguments' { $script:scrubOutput="Starting Microsoft GetHelp Command Line Tool`nError: Invalid command line arguments`nUsage: GetHelpCmd.exe [options]`nExamples:`nGetHelpCmd.exe -S OfficeScrubScenario -AcceptEula" } + 'usage' { $script:scrubOutput="Usage: GetHelpCmd.exe [options]`n00: Success" } 'contradictory' { $script:scrubOutput="09: Failure`n00: Success" } 'bad-exit' { $script:scrubExit=1 } } @@ -939,7 +960,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'}; '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'}; 'invalid-arguments' {'rejected its command line.*process 0'}; 'usage' {'rejected its command line.*process 0'}; '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'} } Assert-OfficeThrows { Invoke-OfficeScrubRecovery $media $workspace 'fixture corruption' } $pattern } $before=$script:scrubLaunches