diff --git a/Install-MicrosoftOffice365.ps1 b/Install-MicrosoftOffice365.ps1 index 82780c9..d0c5a7c 100644 --- a/Install-MicrosoftOffice365.ps1 +++ b/Install-MicrosoftOffice365.ps1 @@ -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' diff --git a/docs/Office365-Deployment.md b/docs/Office365-Deployment.md index 4277693..4ed2f39 100644 --- a/docs/Office365-Deployment.md +++ b/docs/Office365-Deployment.md @@ -109,13 +109,13 @@ 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`. 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. +Recovery downloads a fresh package from Microsoft's evergreen Get Help link into this run's workspace and validates ZIP paths and the executable's Microsoft signature. Only after recovery is selected, it runs `GetHelpCmd.exe -?` and validates the downloaded tool's own usage. It invokes `-S OfficeScrubScenario -AcceptEula`, adding `-OfficeVersion All` only when that switch is advertised. This restores the earlier scrubber's runtime argument detection; observed builds reject the documented optional switch while returning zero. Usage and removal output are logged separately. The scenario must remove all detected Office registrations, 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. 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. +Logs include the trigger, native evidence where available, process result, and scenario result. The management log records stdout/stderr byte counts and bounded beginning/end excerpts; original stream logs retain full output. Get Help must return `0` or `3010` with numbered result `00` or `Scenario completed successfully.`; explicit error text, usage errors, contradictory results and `66`/`68` not-found results stop installation. Every accepted response still requires workers to finish, all detected Office registrations to disappear, and previous Click-to-Run working/source state to clear. Read/verification failures stop deployment. The `gethelp-usage.*.log` and `office-scrub.*.log` files survive cleanup; downloaded non-log files are removed by the same guarded `finally` cleanup as other media. -**Observed Get Help limitation (October 29, 2026):** the current tool can print `Scenario completed successfully.` followed by `ExecutionResultDetails: Uninstall office is running in the background.` and return zero without a terminal scrub result. It launches `powershell.exe -File ...\GetHelpElevated\\Run.ps1` outside the deployment workspace. The observed Microsoft launcher calls `Console.ReadKey()` in `finally` after either success or failure. This path is not reliably unattended. The script reports **background removal requires attended verification**, logs worker PIDs/commands, and stops before replacement installation. A generic success message, missing worker, or even an accompanying `00` cannot turn that background acknowledgement into verified removal. It does not kill the worker, inject a keystroke, modify Microsoft's signed scripts, or increase the timeout to mask the prompt. +When Get Help reports `Uninstall office is running in the background.`, the script now waits instead of failing immediately. It restores the earlier **30-minute background wait** and **60-second quiet interval**. Baseline process identities exclude pre-existing unrelated consoles; newly launched script/installer workers and explicitly identified scrub workers block completion. At least one identified scrub worker must be observed. Worker disappearance alone is insufficient: the script retains process handles to verify identified workers exited with `0` or `3010`, checks all Office registrations and previous deployment state, and requires all conditions to stay clear for the quiet interval. Failed/interrupted workers, inaccessible exit status, no observed worker, remaining products/state or a timeout stop installation. The overall Syncro limit still applies. -Resolve existing workers before another deployment: inspect their console or final diagnostic report, complete any remaining work, and dismiss a finished prompt. A live PowerShell process alone does not reveal whether the scrub is active, failed, or finished. Get Help's observed logger writes `cse.amplify.diagaction.gethelp.officeuninstallalda_.log` directly in the **worker account's** `%LOCALAPPDATA%\DAFs` directory (not a subfolder named for the scenario). No report was found in the checked Administrator/System locations on the affected endpoint, so removal remains unverified. Do not infer success from missing logs or reuse the generated `GetHelpElevated` payload on the next deployment. +**Visible last-resort window:** Get Help may launch `powershell.exe -File ...\GetHelpElevated\\Run.ps1` outside the deployment workspace and display it in a user's session. Leave it open during cleanup. The observed Microsoft launcher waits for a key in `finally` after either success or failure; dismiss a completed `Press any key to exit` prompt so verification can proceed. The window is not locked against closure. Get Help exposes no documented Office-scrub switch for that, and a handler registered in the RMM parent cannot protect another process; Windows still terminates a console process after a close signal ([console handler behavior](https://learn.microsoft.com/en-us/windows/console/handlerroutine)). The script monitors worker exit codes and endpoint state instead of modifying signed vendor scripts or injecting UI input. A successful process exit alone never proves removal. Get Help's diagnostic reports, when produced, are directly in the worker account's `%LOCALAPPDATA%\DAFs` as `cse.amplify.diagaction.gethelp.officeuninstallalda_.log`. Existing active workers block a new deployment; never reuse their payloads for the next run. 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). @@ -193,6 +193,8 @@ Run `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\Install-Mic `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. +Restored scrub tests cover advertised/unsupported arguments, both result formats, background acknowledgement, delayed inventory, a restarted quiet interval, a worker left at the keypress prompt, closed/failed workers, unknown worker identity, missing observed workers, stale state, and the 30-minute bound. An inert PowerShell child verifies that the retained process handle preserves a nonzero exit code after the child terminates. No actual scrubber is executed by the suite. + Endpoint acceptance still requires a VM pilot: existing MSI/C2R/Store Office, machine/per-user Teams and OneDrive, a logged-off profile, standard-user sign-in, wrong-license rejection, download failure, and the restart path. Verify new Outlook and Teams registration at sign-in, OneDrive migration, and that delayed cleanup preserves reinstalled apps. The implementation has not been run destructively against a real endpoint during development. ## Maintaining deployment definitions diff --git a/rmm/Install-MicrosoftOffice365.ps1 b/rmm/Install-MicrosoftOffice365.ps1 index b03bf40..08aa783 100644 --- a/rmm/Install-MicrosoftOffice365.ps1 +++ b/rmm/Install-MicrosoftOffice365.ps1 @@ -8,6 +8,9 @@ # Deployment clears prior run artifacts, downloads fresh media before uninstalling, and leaves only logs. # Confirmed ODT removal corruption or residual state can trigger one Microsoft Get Help scrub. # Scrub downloads are on demand, may display a child window, and honor DeferReboot after verification. +# Background scrub waits up to 30 minutes plus verification within Syncro's overall limit. +# Leave its window open during removal; dismiss a completed 'Press any key to exit' prompt. +# The child window cannot be reliably locked; failed/interrupted monitored workers stop installation. # Pending user tasks keep synchronization markers and fetch their helper live. Active installers block cleanup. # [string]$OfficeSubscription - Required; use the exact subscription names in the guide. # [string]$OfficeArchitecture - Auto (default), 64, 32 diff --git a/tests/Install-MicrosoftOffice365.Tests.ps1 b/tests/Install-MicrosoftOffice365.Tests.ps1 index dcfd4d0..6b9be37 100644 --- a/tests/Install-MicrosoftOffice365.Tests.ps1 +++ b/tests/Install-MicrosoftOffice365.Tests.ps1 @@ -918,6 +918,85 @@ try { $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.' } + # Restore runtime syntax detection instead of trusting stale published switches. + & { + $usage='GetHelpCmd.exe -S OfficeScrubScenario -AcceptEula' + Assert-OfficeTest ((Get-OfficeScrubArguments 0 $usage) -eq '-S OfficeScrubScenario -AcceptEula') 'Current tool usage must omit unsupported OfficeVersion.' + Assert-OfficeTest ((Get-OfficeScrubArguments 0 ($usage + "`n -OfficeVersion ")) -eq '-S OfficeScrubScenario -AcceptEula -OfficeVersion All') 'A tool advertising OfficeVersion must request all versions.' + Assert-OfficeThrows { Get-OfficeScrubArguments 1 $usage } 'Could not validate' + Assert-OfficeThrows { Get-OfficeScrubArguments 0 ($usage + "`nError: Invalid command line arguments") } 'Could not validate' + Assert-OfficeThrows { Get-OfficeScrubArguments 0 'No OfficeScrubScenario example' } 'Could not validate' + } + & { + function Get-CimInstance { + param($ClassName,$Filter) + Assert-OfficeTest ($ClassName -eq 'Win32_Process' -and $Filter.Contains("Name='powershell.exe'")) 'Worker monitoring must inspect detached script hosts.' + [pscustomobject]@{Name='powershell.exe';ProcessId=$PID;CommandLine='self'} + [pscustomobject]@{Name='powershell.exe';ProcessId=9701;CommandLine='powershell.exe -File C:\Temp\GetHelpElevated\abc\Run.ps1'} + [pscustomobject]@{Name='msiexec.exe';ProcessId=9702;CommandLine='msiexec.exe /V'} + [pscustomobject]@{Name='OfficeClickToRun.exe';ProcessId=9703;CommandLine='OfficeClickToRun.exe /service'} + [pscustomobject]@{Name='OfficeClickToRun.exe';ProcessId=9704;CommandLine='OfficeClickToRun.exe /user'} + [pscustomobject]@{Name='msiexec.exe';ProcessId=9705;CommandLine='msiexec.exe /x {fixture}'} + } + $workers=@(Get-OfficeScrubWorkers) + Assert-OfficeTest ($workers.Count -eq 2 -and 9701 -in $workers.ProcessId -and 9705 -in $workers.ProcessId) 'Detached cleanup and active MSI workers matter; the caller and idle service hosts do not.' + } + # Verify actual process-handle retention using only an inert child, never a scrubber. + & { + $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes('Start-Sleep -Milliseconds 1500; exit 7')) + $probe=Start-Process -FilePath (Join-Path $PSHOME 'powershell.exe') -ArgumentList "-NoProfile -NonInteractive -EncodedCommand $encoded" -WindowStyle Hidden -PassThru + $held=$null + try { + $identity=Get-CimInstance Win32_Process -Filter "ProcessId=$($probe.Id)" -ErrorAction Stop + $held=Open-OfficeScrubWorkerHandle $identity + Assert-OfficeTest ($held.WaitForExit(10000) -and $held.ExitCode -eq 7) 'A held handle must preserve a failed worker exit after its PID disappears.' + Assert-OfficeThrows { Open-OfficeScrubWorkerHandle ([pscustomobject]@{ProcessId=$PID;CreationDate=[datetime]'2000-01-01'}) } 'Process identity changed' + } finally { if ($held) { $held.Dispose() }; $probe.Dispose() } + } + # 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-OfficeScrubWorkers { + $script:waitPoll++ + if ($script:waitMode -eq 'process-error') { throw 'Process inventory unreadable' } + $existing + if ($script:waitMode -ne 'no-worker' -and ($script:waitPoll -le 2 -or $script:waitMode -eq 'keypress')) { $fixtureScrubWorker } + if ($script:waitMode -eq 'quiet-reset' -and $script:waitPoll -eq 5) { [pscustomobject]@{Name='setup.exe';ProcessId=9702;CreationDate=$fixtureScrubWorker.CreationDate;CommandLine='setup.exe'} } + } + function Open-OfficeScrubWorkerHandle { + param($Worker) + $script:openCalls++ + if ($script:waitMode -eq 'lost-handle') { throw 'Could not monitor scrub worker PID 9701' } + $handle=[pscustomobject]@{ExitCode=$(if ($script:waitMode -eq 'closed') {-1073741510} elseif ($script:waitMode -eq 'failed') {1} elseif ($script:waitMode -eq 'restart') {3010} else {0})} + $handle | Add-Member ScriptProperty HasExited { $script:waitPoll -gt 2 -and $script:waitMode -ne 'keypress' } + $handle | Add-Member ScriptMethod Dispose { $script:disposed++ } + $handle + } + function Get-OfficeSuiteInventory { + if ($script:waitMode -eq 'inventory-error') { throw 'Office inventory unreadable' } + if ($script:waitMode -eq 'remaining' -or ($script:waitMode -eq 'delayed' -and $script:waitPoll -le 4)) { [pscustomobject]@{DisplayName='Old Office'} } + } + function Get-OfficeClickToRunState { + 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')) { + $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'} } + Assert-OfficeThrows { Wait-OfficeScrubRemoval @($existing) } $pattern + 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.' + } + } # A scrub requires both a successful scenario/process result and independently # verified removal. Every attempt is bounded to one and cleanup retains its logs. & { @@ -930,13 +1009,26 @@ try { } function Invoke-OfficeProcess { param($FilePath,$Arguments,$LogPrefix) + if ($Arguments -eq '-?') { + $script:usageCalls++ + Set-Content -LiteralPath "$LogPrefix.stdout.log" -Value $(if ($script:scrubMode -eq 'bad-help') {'Usage unavailable'} else {'GetHelpCmd.exe -S OfficeScrubScenario -AcceptEula'}) + Set-Content -LiteralPath "$LogPrefix.stderr.log" -Value '' + return 0 + } $script:scrubLaunches++ 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 } + function Get-OfficeScrubWorkers { if ($script:scrubMode -eq 'preexisting-worker') { [pscustomobject]@{Name='powershell.exe';ProcessId=8000;CommandLine='powershell.exe -File C:\Temp\GetHelpElevated\old\Run.ps1'} } } + function Wait-OfficeScrubRemoval { + param($ExistingWorkers) + $script:backgroundWaits++ + if ($script:scrubMode -eq 'background-no-worker') { throw 'Get Help background removal did not finish verification within the allowed time.' } + } function Get-CimInstance { + if ($script:scrubMode -eq 'preexisting-worker') { Get-OfficeScrubWorkers } if ($script:scrubMode -eq 'running') { [pscustomobject]@{Name='GetHelpCmd.exe'} } if ($script:scrubMode -eq 'background') { [pscustomobject]@{Name='powershell.exe';ProcessId=7064;CommandLine='powershell.exe -File C:\Windows\SystemTemp\GetHelpElevated\d509ee113e5346fa82eded7e01f47f69\Run.ps1'} } } @@ -945,9 +1037,9 @@ 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','invalid-arguments','usage','background','background-no-worker','background-with-00','generic-success','contradictory','bad-exit','running','remaining','inventory-error','stale')) { + 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.' + $media=[pscustomobject]@{}; $script:scrubExit=0; $script:scrubOutput='00: Successfully completed this scenario.'; $script:backgroundWaits=0; $script:usageCalls=0 switch ($script:scrubMode) { 'restart' { $script:scrubExit=3010 } 'failure' { $script:scrubOutput='09: Failure to remove Office.' } @@ -958,24 +1050,29 @@ try { 'usage' { $script:scrubOutput="Usage: GetHelpCmd.exe [options]`n00: Success" } { $_ -like 'background*' } { $script:scrubOutput="Starting Microsoft GetHelp Command Line Tool`nDiagnostic action completed.`nScenario completed successfully.`nExecutionResultDetails: Uninstall office is running in the background."; if ($_ -eq 'background-with-00') { $script:scrubOutput += "`n00: Success" } } 'generic-success' { $script:scrubOutput='Scenario completed successfully.' } + 'text-error' { $script:scrubOutput="Error: Removal failed`nScenario completed successfully." } + 'background-error' { $script:scrubOutput += "`nError: Removal failed" } + 'background-bad-exit' { $script:scrubExit=1 } 'contradictory' { $script:scrubOutput="09: Failure`n00: Success" } 'bad-exit' { $script:scrubExit=1 } } - if ($script:scrubMode -in @('success','restart')) { + if ($script:scrubMode -in @('success','restart','generic-success','background-with-00')) { $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'}; 'invalid-arguments' {'rejected its command line.*process 0'}; 'usage' {'rejected its command line.*process 0'}; { $_ -like 'background*' } {'background removal requires attended verification.*launcher exit 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'} } + $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'} } 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.' + Assert-OfficeTest ($script:backgroundWaits -eq $(if ($script:scrubMode -in @('background','background-no-worker','background-with-00')) {1} else {0})) 'Only an accepted background launch may enter the completion wait.' $before=$script:scrubLaunches Assert-OfficeThrows { Invoke-OfficeScrubRecovery $media $workspace 'second attempt' } 'already attempted' Assert-OfficeTest ($script:scrubLaunches -eq $before) 'Failure must not create a scrub loop.' $warnings=Complete-OfficeDeploymentFiles $workspace - if ($script:scrubMode -in @('running','background')) { Assert-OfficeTest ($warnings.Count -gt 0 -and (Test-Path -LiteralPath (Join-Path $workspace 'GetHelp.zip'))) 'Surviving scrub workers must retain in-use media.' } + if ($script:scrubMode -in @('running','background','preexisting-worker')) { Assert-OfficeTest ($warnings.Count -gt 0 -and (Test-Path -LiteralPath (Join-Path $workspace 'GetHelp.zip'))) 'Surviving scrub workers must retain in-use media.' } else { Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath (Join-Path $workspace 'GetHelp.zip'))) 'Scrub download must be removed on success and failure.' - if ($script:scrubMode -ne 'download') { Assert-OfficeTest (Test-Path -LiteralPath (Join-Path $workspace 'office-scrub.stdout.log')) 'Scrub result logs must survive cleanup.' } + if ($script:scrubMode -notin @('download','bad-help')) { Assert-OfficeTest (Test-Path -LiteralPath (Join-Path $workspace 'office-scrub.stdout.log')) 'Scrub result logs must survive cleanup.' } } } Assert-OfficeTest (Test-OfficeStagingInUse $testRoot @([pscustomobject]@{Name='cscript.exe';CommandLine='cscript.exe C:\Temp\OffScrubC2R.vbs ALL'})) 'Detached Office scrub scripts must block a new deployment and media cleanup.' @@ -998,7 +1095,9 @@ try { $quoted=[pscustomobject]@{Name='powershell.exe';CommandLine='powershell.exe -File "C:\Temp Folder\GETHELPELEVATED\abc\run.ps1" "C:\Temp Folder\GETHELPELEVATED\abc"'} Assert-OfficeTest (Test-OfficeStagingInUse $workspace @($quoted)) 'Quoted Get Help worker paths must be recognized case-insensitively.' $ordinary=@([pscustomobject]@{Name='powershell.exe';CommandLine='powershell.exe -File C:\Tools\Run.ps1'},[pscustomobject]@{Name='OfficeClickToRun.exe';CommandLine='OfficeClickToRun.exe /service'},[pscustomobject]@{Name='OfficeClickToRun.exe';CommandLine='OfficeClickToRun.exe /user'}) - Assert-OfficeTest (!(Test-OfficeStagingInUse $workspace $ordinary)) 'Unrelated PowerShell and idle Click-to-Run hosts must not be mistaken for scrub workers.' + $ordinary += @([pscustomobject]@{Name='msiexec.exe';CommandLine='msiexec.exe /V'},[pscustomobject]@{Name='msiexec.exe';CommandLine='msiexec.exe /Embedding fixture'}) + Assert-OfficeTest (!(Test-OfficeStagingInUse $workspace $ordinary)) 'Unrelated PowerShell and idle Click-to-Run/MSI hosts must not block completed cleanup.' + Assert-OfficeTest (Test-OfficeStagingInUse $workspace @([pscustomobject]@{Name='msiexec.exe';CommandLine='msiexec.exe /x {fixture} /quiet'})) 'Active MSI uninstall clients must still protect the workspace.' } # Deployment resolves release metadata and deletes it on success or failure. & {