diff --git a/Install-MicrosoftOffice365.ps1 b/Install-MicrosoftOffice365.ps1 index 76711fd..82780c9 100644 --- a/Install-MicrosoftOffice365.ps1 +++ b/Install-MicrosoftOffice365.ps1 @@ -379,7 +379,8 @@ function Clear-OfficePreviousDeploymentFiles { $roots = @(Get-OfficeDeploymentRoots) $processes = @(Get-CimInstance Win32_Process -ErrorAction Stop) foreach ($root in $roots) { - if (Test-OfficeStagingInUse $root $processes) { throw "A surviving installer is running. Stop the previous deployment before removing old artifacts in $root." } + $blocking = @(Get-OfficeBlockingProcesses $root $processes) + if ($blocking.Count) { throw "A surviving installer is running: $(($blocking | ForEach-Object { "$($_.Name) (PID $($_.ProcessId))" }) -join '; '). Resolve the previous deployment before removing old artifacts in $root. GetHelpElevated Run.ps1 can remain at a 'Press any key to exit' prompt after success or failure; inspect its final report before dismissing it." } Assert-OfficeManagedPath $root (Join-Path $root 'path-check') } $tasks = @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -match '^Emberkom-OfficeCleanup-[a-f0-9]{32}-S-1-[\d-]+$' }) @@ -410,18 +411,25 @@ function Clear-OfficePreviousDeploymentFiles { } } -function Test-OfficeStagingInUse { +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) { - if ($process.Name -in @('setup.exe', 'odt.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'GetHelpCmd.exe', 'SaRAcmd.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe')) { return $true } - if ($process.Name -eq 'OfficeClickToRun.exe' -and $process.CommandLine -notmatch '(?i)\s/(service|user)\s*$') { return $true } - if ($process.CommandLine -match '(?i)\b(OffScrub[^\s"\\/]*\.(vbs|ps1)|OfficeScrubScenario)\b') { return $true } + 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 } + # Current Get Help detaches PowerShell into its own temp directory. Its + # command line contains neither OfficeScrubScenario nor our workspace. + if ($process.CommandLine -match '(?i)[\\/]GetHelpElevated[\\/][^\\/"\s]+[\\/]Run\.ps1(?:["\s]|$)') { $process; continue } foreach ($value in @($process.CommandLine, $process.ExecutablePath)) { - if ($value -and $value.IndexOf($Workspace, [StringComparison]::OrdinalIgnoreCase) -ge 0) { return $true } + if ($Workspace -and $value -and $value.IndexOf($Workspace, [StringComparison]::OrdinalIgnoreCase) -ge 0) { $process; break } } } - return $false +} + +function Test-OfficeStagingInUse { + param([string]$Workspace, [object[]]$Processes) + return @(Get-OfficeBlockingProcesses $Workspace $Processes).Count -gt 0 } function Complete-OfficeDeploymentFiles { @@ -951,6 +959,18 @@ function Invoke-OfficeScrubRecovery { 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." + } $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 03a7641..4277693 100644 --- a/docs/Office365-Deployment.md +++ b/docs/Office365-Deployment.md @@ -113,11 +113,15 @@ Recovery downloads a fresh package from Microsoft's evergreen Get Help link into 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. +**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. + +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. + 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). Other ODT errors still stop for diagnosis. No automatic scrub is attempted after replacement installation begins, including a failed `RemoveMSI` check that could occur after the new suite is installed. A deployment already running an older script continues using that downloaded code: let it finish before starting another deployment. -Native installer processes, including ODT and the conditional scrub, are awaited until they and their process trees exit; there is no separate 30-minute installer cutoff. Syncro's two-hour limit remains the overall limit and is not reset between phases. Post-process verification allows five minutes for registration and background-worker state to settle; surviving Get Help/OffScrub workers block installation and artifact deletion. Waiting for active user cleanup and its reinstall-transition lock allows 20 minutes; the per-user scheduled task limit is 30 minutes. Those tasks may also run later for absent users. These allowances do not guarantee every endpoint finishes within two hours. If the RMM terminates a run, check for surviving installer processes before rerunning; the script does not kill an active installer to meet a time budget. +Native installer processes, including ODT and the conditional scrub, are awaited using `Start-Process -Wait`; there is no separate 30-minute installer cutoff. Get Help can detach a worker beyond that wait, as described above. Syncro's two-hour limit remains the overall limit and is not reset between phases. After a terminal scrub result, verification allows five minutes for registration and background-worker state to settle. Surviving Get Help/OffScrub workers, including `GetHelpElevated\...\Run.ps1`, block installation, new deployment downloads, and artifact deletion even outside the current workspace. Waiting for active user cleanup and its reinstall-transition lock allows 20 minutes; the per-user scheduled task limit is 30 minutes. Those tasks may also run later for absent users. These allowances do not guarantee every endpoint finishes within two hours. If the RMM terminates a run, check for surviving installer processes before rerunning; the script does not kill an active installer to meet a time budget. Transient failures get bounded recovery before deployment stops: diff --git a/tests/Install-MicrosoftOffice365.Tests.ps1 b/tests/Install-MicrosoftOffice365.Tests.ps1 index ee732b5..dcfd4d0 100644 --- a/tests/Install-MicrosoftOffice365.Tests.ps1 +++ b/tests/Install-MicrosoftOffice365.Tests.ps1 @@ -936,13 +936,16 @@ try { Set-Content -LiteralPath "$LogPrefix.stderr.log" -Value '' $script:scrubExit } - function Get-CimInstance { if ($script:scrubMode -eq 'running') { [pscustomobject]@{Name='GetHelpCmd.exe'} } } + function Get-CimInstance { + 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'} } + } function Get-OfficeSuiteInventory { if ($script:scrubMode -eq 'remaining') { [pscustomobject]@{DisplayName='Leftover MSI Office';WindowsInstaller=1} } 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','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','background','background-no-worker','background-with-00','generic-success','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) { @@ -953,6 +956,8 @@ try { '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" } + { $_ -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.' } 'contradictory' { $script:scrubOutput="09: Failure`n00: Success" } 'bad-exit' { $script:scrubExit=1 } } @@ -960,14 +965,14 @@ 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'}; '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'} } + $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'} } Assert-OfficeThrows { Invoke-OfficeScrubRecovery $media $workspace 'fixture corruption' } $pattern } $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 -eq 'running') { 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')) { 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.' } @@ -975,6 +980,26 @@ try { } 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.' } + # Get Help's detached signed launcher lives outside the deployment workspace + # and can remain at Console.ReadKey after either success or failure. + & { + $worker=[pscustomobject]@{Name='powershell.exe';ProcessId=7064;CommandLine='"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File C:\Windows\SystemTemp\GetHelpElevated\d509ee113e5346fa82eded7e01f47f69\Run.ps1 C:\Windows\SystemTemp\GetHelpElevated\d509ee113e5346fa82eded7e01f47f69'} + $root=Join-Path $testRoot 'detached-gethelp'; $workspace=Join-Path $root ('a'*32) + $null=[IO.Directory]::CreateDirectory($workspace) + $payload=Join-Path $workspace 'GetHelp.zip'; Set-Content -LiteralPath $payload -Value 'fixture' + function Get-CimInstance { $worker } + function Get-OfficeDeploymentRoots { $root } + function Get-ScheduledTask { throw 'Worker guard must run before retiring tasks.' } + Assert-OfficeTest (Test-OfficeStagingInUse $workspace @($worker)) 'GetHelpElevated Run.ps1 must block cleanup despite not naming our workspace.' + Assert-OfficeTest (@(Get-OfficeBlockingProcesses $workspace @($worker)).Count -eq 1) 'A worker must be returned once for diagnostics.' + Assert-OfficeThrows { Clear-OfficePreviousDeploymentFiles } 'surviving installer.*powershell.exe \(PID 7064\)' + $warnings=Complete-OfficeDeploymentFiles $workspace + Assert-OfficeTest ($warnings.Count -gt 0 -and (Test-Path -LiteralPath $payload)) 'Detached Get Help workers must preserve media on failure as well as block fresh downloads.' + $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.' + } # Deployment resolves release metadata and deletes it on success or failure. & { $script:historyPaths=@()