From 52aa59a70c32f49862cf073fa5129135c88c6fe5 Mon Sep 17 00:00:00 2001 From: ek-dyoder Date: Thu, 29 Oct 2026 15:05:37 -0400 Subject: [PATCH] add scrubber back into deployment script --- Install-MicrosoftOffice365.ps1 | 132 ++++++++++++++--- README.md | 2 +- docs/Office365-Deployment.md | 22 ++- rmm/Install-MicrosoftOffice365.ps1 | 2 + tests/Install-MicrosoftOffice365.Tests.ps1 | 163 +++++++++++++++++++-- 5 files changed, 283 insertions(+), 38 deletions(-) diff --git a/Install-MicrosoftOffice365.ps1 b/Install-MicrosoftOffice365.ps1 index 87e594a..03ef798 100644 --- a/Install-MicrosoftOffice365.ps1 +++ b/Install-MicrosoftOffice365.ps1 @@ -32,6 +32,10 @@ function Get-OfficeDeploymentDefinitions { OdtPage = 'https://www.microsoft.com/en-us/download/details.aspx?id=49117' OdtDownloadPattern = 'https://download\.microsoft\.com/[^"\s<>]+/officedeploymenttool_[a-zA-Z0-9_-]+\.exe' 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' + ScrubRecoveryExitCodes = @(17002, 17004) HelperVersion = 'EmberkomOfficeUserCleanup-v5' Language = 'en-us' OfficeBuildPattern = '^16\.0\.\d+\.\d+$' @@ -250,7 +254,7 @@ function Test-OfficeDownloadLinks { param($Options) $definitions = Get-OfficeDeploymentDefinitions [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 - $links = @($definitions.OdtPage, "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1") + $links = @($definitions.OdtPage, "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1", $definitions.GetHelpUrl) if ($Options.OfficeFeatureRelease) { $links += $definitions.OfficeReleaseHistory } $channel = $definitions.OfficeCdnChannels[$Options.UpdateChannel] $links += "https://officecdn.microsoft.com/pr/$channel/Office/Data/v$($Options.OfficeArchitecture).cab" @@ -406,8 +410,9 @@ function Test-OfficeStagingInUse { 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', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe')) { 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')) { 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 } foreach ($value in @($process.CommandLine, $process.ExecutablePath)) { if ($value -and $value.IndexOf($Workspace, [StringComparison]::OrdinalIgnoreCase) -ge 0) { return $true } } @@ -525,7 +530,7 @@ function Invoke-OfficeProcess { } } -function Write-OfficeSetupDiagnostics { +function Get-OfficeSetupLogFiles { param( [DateTime]$SinceUtc, [string[]]$SearchRoots = @([IO.Path]::GetTempPath(), "$env:WINDIR\Temp", "$env:WINDIR\SystemTemp") @@ -542,7 +547,16 @@ function Write-OfficeSetupDiagnostics { } } catch { $null = Write-Output "Could not search native Office logs in ${root}: $($_.Exception.Message)" } }) - $files = @($files | Sort-Object FullName -Unique | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First $definitions.SetupDiagnosticFileLimit) + $files | Sort-Object FullName -Unique | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First $definitions.SetupDiagnosticFileLimit +} + +function Write-OfficeSetupDiagnostics { + param( + [DateTime]$SinceUtc, + [string[]]$SearchRoots = @([IO.Path]::GetTempPath(), "$env:WINDIR\Temp", "$env:WINDIR\SystemTemp") + ) + $definitions = Get-OfficeDeploymentDefinitions + $files = @(Get-OfficeSetupLogFiles -SinceUtc $SinceUtc -SearchRoots $SearchRoots) if (!$files.Count) { $null = Write-Output "No recent nonempty native Office logs found in: $($SearchRoots -join '; '). Empty ODT stdout/stderr files do not contain the underlying setup error." return @@ -832,21 +846,94 @@ function Get-OfficeClickToRunState { [pscustomobject]@{ Present=($present -or $null -ne $service); SourceReferences=$sources; WorkingConfiguration=$working } } -function Assert-OfficeFreshInstallState { - $cleared = Wait-OfficeResult { +function Test-OfficeFreshInstallState { + [bool](Wait-OfficeResult { $state = Get-OfficeClickToRunState !$state.SourceReferences.Count -and !$state.WorkingConfiguration.Count - } 'removal of previous Click-to-Run working configuration and deployment source references' - if (!$cleared) { + } 'removal of previous Click-to-Run working configuration and deployment source references') +} + +function Assert-OfficeFreshInstallState { + if (!(Test-OfficeFreshInstallState)) { $state = Get-OfficeClickToRunState throw "Click-to-Run still retains previous deployment state after ODT removal. Installation stopped to prevent reuse of old content. Working configuration: $($state.WorkingConfiguration -join ', '). Source references: $($state.SourceReferences -join '; '). Arrange an attended Office repair/scrub: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)" } } +function Get-OfficeRemovalCorruptionEvidence { + param([DateTime]$SinceUtc) + $finishedUtc = [DateTime]::UtcNow + foreach ($file in @(Get-OfficeSetupLogFiles -SinceUtc $SinceUtc)) { + try { + foreach ($line in @(Get-Content -LiteralPath $file.FullName -Tail (Get-OfficeDeploymentDefinitions).SetupDiagnosticTailLines -ErrorAction Stop)) { + # An exit code alone cannot distinguish corrupt state from network, + # source or policy problems. Require a removal-specific native error + # timestamped during THIS attempt, not an old error in a live log. + if ($line -notmatch '(?i)InvalidDirectory' -or $line -notmatch '(?i)REMOVEINSTALLATION') { continue } + if ($line -notmatch '^\s*(\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2}:\d{2}\.\d{3})\s') { continue } + $stamp = [DateTime]::MinValue + if (![DateTime]::TryParseExact($Matches[1], 'M/d/yyyy H:mm:ss.fff', [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::AssumeLocal, [ref]$stamp)) { continue } + if ($stamp.ToUniversalTime() -lt $SinceUtc.AddSeconds(-1) -or $stamp.ToUniversalTime() -gt $finishedUtc) { continue } + return [pscustomobject]@{ Path=$file.FullName; Detail=$line } + } + } catch { $null = Write-Output "Could not classify Office removal failure from $($file.FullName): $($_.Exception.Message)" } + } +} + +function Initialize-OfficeScrubMedia { + param([string]$Workspace) + $definitions = Get-OfficeDeploymentDefinitions + $archivePath = Join-Path $Workspace 'GetHelp.zip' + $folder = Join-Path $Workspace 'GetHelp' + if ((Test-Path -LiteralPath $archivePath) -or (Test-Path -LiteralPath $folder)) { throw 'Scrub media already exists in this run; refusing to reuse it or repeat recovery.' } + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + Save-OfficeDownload $definitions.GetHelpUrl $archivePath + # Validate every entry before extraction, including on older PS 5.1 archive modules. + Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem + $archive = [IO.Compression.ZipFile]::OpenRead($archivePath) + try { + foreach ($entry in $archive.Entries) { + if (!$entry.FullName -or $entry.FullName.Contains(':')) { throw 'Unexpected path in Get Help archive.' } + Assert-OfficeManagedPath $folder ([IO.Path]::Combine($folder, $entry.FullName)) + } + } finally { $archive.Dispose() } + # Tools.ps1 overrides Expand-Archive with a Path-only wrapper. + Microsoft.PowerShell.Archive\Expand-Archive -LiteralPath $archivePath -DestinationPath $folder -ErrorAction Stop + $files = @(Get-OfficeManagedFiles $Workspace $folder) + $executables = @($files | Where-Object { $_.Name -eq $definitions.GetHelpExecutable }) + if ($executables.Count -ne 1) { throw "Microsoft download did not contain exactly one $($definitions.GetHelpExecutable)." } + Assert-OfficeMicrosoftSignature $executables[0].FullName + $executables[0].FullName +} + +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.' + $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) + $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." } + $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' + if (!$removed) { throw "Office remains after Get Help scrub: $((Get-OfficeSuiteInventory).DisplayName -join '; '). Installation stopped." } + Assert-OfficeFreshInstallState + $null = Write-Output 'Office scrub recovery verified. Reporting restart required; DeferReboot controls whether installation can finish before that restart.' + return 3010 +} + function Remove-OfficeSuite { param($Media, [string]$Workspace) - # Get Help can create an interactive elevated child despite a hidden SYSTEM parent. - # Never fall back to it automatically. ODT owns the supported silent removal path. + # ODT is the normal path. A single Get Help scrub is reserved for evidence of + # broken removal or residual state, before replacement installation begins. $existing = @(Get-OfficeSuiteInventory) $msi = @($existing | Where-Object { $_.WindowsInstaller -eq 1 }) if ($msi.Count) { $null = Write-Output "MSI Office will be removed by ODT RemoveMSI before it installs the replacement suite: $($msi.DisplayName -join '; ')." } @@ -857,15 +944,25 @@ function Remove-OfficeSuite { } if (!$Media.RemovalConfig -or !(Test-Path -LiteralPath $Media.RemovalConfig -PathType Leaf)) { throw 'The staged silent Office removal configuration is missing.' } $null = Write-Output 'Silently removing Click-to-Run Office, including incomplete deployments, Visio and Project, with ODT.' + $startedUtc = [DateTime]::UtcNow $code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.RemovalConfig)`"" (Join-Path $Workspace 'office-remove') - $manual = "No interactive scrubber was launched. Arrange an attended manual scrub if needed: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)" - if ($code -notin @(0, 3010)) { throw "Silent ODT Office removal failed (exit $code). See logs in $Workspace. $manual" } + if ($code -notin @(0, 3010)) { + if ($code -in (Get-OfficeDeploymentDefinitions).ScrubRecoveryExitCodes) { + $evidence = Get-OfficeRemovalCorruptionEvidence -SinceUtc $startedUtc + if ($evidence) { + $null = Write-Output "Office scrub trigger evidence: $($evidence.Path) : $($evidence.Detail)" + return Invoke-OfficeScrubRecovery $Media $Workspace "ODT removal exit $code with a current REMOVEINSTALLATION InvalidDirectory error." + } + } + throw "Silent ODT Office removal failed (exit $code). No confirmed removal-corruption evidence was found; automatic scrub was not selected. See logs in $Workspace. Manual troubleshooting: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)" + } if ($code -eq 3010) { return 3010 } $removed = Wait-OfficeResult { @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 }).Count -eq 0 } 'Click-to-Run Office removal registration' if (!$removed) { $remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 }) - throw "Office remains after silent ODT removal: $($remaining.DisplayName -join '; '). Installation stopped. $manual" + return Invoke-OfficeScrubRecovery $Media $Workspace "Office remains after successful ODT removal: $($remaining.DisplayName -join '; ')." } + if (!(Test-OfficeFreshInstallState)) { return Invoke-OfficeScrubRecovery $Media $Workspace 'Previous Click-to-Run working configuration or deployment source references remain after successful ODT removal.' } return 0 } @@ -1129,11 +1226,11 @@ function Install-OfficeMedia { param($Options, $Media, [string]$Workspace) $msi = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 }) $code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.Config)`"" (Join-Path $Workspace 'office-install') - if ($code -notin @(0, 3010)) { throw "Office installation failed (exit $code). Diagnostic logs remain in $Workspace; disposable media is cleaned up after installer processes finish. Review the Native Office log/detail entries in the diagnostic log; Click-to-Run writes its underlying errors to the execution account's temp folder or Windows\Temp. The exit code alone does not identify the cause. No interactive scrubber was launched." } + if ($code -notin @(0, 3010)) { throw "Office installation failed (exit $code). Diagnostic logs remain in $Workspace; disposable media is cleaned up after installer processes finish. Review the Native Office log/detail entries in the diagnostic log; Click-to-Run writes its underlying errors to the execution account's temp folder or Windows\Temp. The exit code alone does not identify the cause. No automatic scrub is attempted after replacement installation begins." } $msiRemoved = Wait-OfficeResult { @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 }).Count -eq 0 } 'legacy MSI Office removal by ODT' if (!$msiRemoved) { $remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 }) - throw "MSI Office remains after ODT RemoveMSI: $($remaining.DisplayName -join '; '). Deployment is incomplete; the new suite may already be installed. No interactive scrubber was launched. Arrange an attended manual scrub if needed: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)" + throw "MSI Office remains after ODT RemoveMSI: $($remaining.DisplayName -join '; '). Deployment is incomplete; the new suite may already be installed. No automatic scrub is attempted after replacement installation begins. Arrange an attended manual scrub if needed: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)" } $platform = if ($Options.OfficeArchitecture -eq '64') { 'x64' } else { 'x86' } $verified = Wait-OfficeResult { @@ -1193,6 +1290,7 @@ function Invoke-OfficeDeployment { UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams; OfficeRemovalMethod='SilentODT'; DeferReboot=$Options.DeferReboot Workspace=$null; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps; MediaDownloaded=$false WritablePaths=$writablePaths; DownloadChecks=$downloadChecks; ClickToRunState=$state; OfficeFeatureRelease=$Options.OfficeFeatureRelease; MetadataResolved=$false + ScrubRecoveryPolicy='One Get Help scrub for confirmed removal corruption or residual state after successful ODT removal; deployment only.' NextStep='Set ValidateBeforeChanges=false to download, verify, deploy, and clean up installation media. Prerequisites are checked again.' } } @@ -1215,7 +1313,7 @@ function Invoke-OfficeDeployment { $removalCode = Remove-OfficeSuite $media $workspace if ($removalCode -eq 3010 -and !(Test-OfficeCanDeferRestart $Options 'Office')) { $null = Write-Output 'Office removal requires a restart. Restart and rerun; replacement installation has not started.' - $receipt = [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @(); ArtifactCleanupPending=$false } + $receipt = [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @(); ArtifactCleanupPending=$false; ScrubRecoveryAttempted=[bool]$media.ScrubAttempted; ScrubRecoveryReason=$media.ScrubReason } return $receipt } Assert-OfficeFreshInstallState @@ -1235,7 +1333,7 @@ function Invoke-OfficeDeployment { $null = Write-Output "$provisionedApps provisioned for all users; OneDrive is installed per-machine. Users may need to sign out and back in to register the apps." $null = Write-Output 'Windows work-account/WAM sign-in is preserved; Windows SSO can sign Office in again. App installation does not grant Teams or mailbox entitlements.' $completed = $true - $receipt = [pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if (($pending.Count -or $registrationFailures.Count) -and $code -eq 0) { 2 } else { $code }); RestartRequired=($code -eq 3010); DeferReboot=$Options.DeferReboot; ValidateBeforeChanges=$false; Workspace = $workspace; UserCleanupWorkspace=$(if ($profiles.Count) { $userWorkspace } else { $null }); PendingUserSids = $pending; UserCleanupRegistrationFailures = $registrationFailures; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version; MediaDownloaded=$true; ArtifactCleanupPending=$false } + $receipt = [pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if (($pending.Count -or $registrationFailures.Count) -and $code -eq 0) { 2 } else { $code }); RestartRequired=($code -eq 3010); DeferReboot=$Options.DeferReboot; ValidateBeforeChanges=$false; Workspace = $workspace; UserCleanupWorkspace=$(if ($profiles.Count) { $userWorkspace } else { $null }); PendingUserSids = $pending; UserCleanupRegistrationFailures = $registrationFailures; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version; MediaDownloaded=$true; ArtifactCleanupPending=$false; ScrubRecoveryAttempted=[bool]$media.ScrubAttempted; ScrubRecoveryReason=$media.ScrubReason } return $receipt } finally { if ($workspace) { diff --git a/README.md b/README.md index e8218e9..58278d4 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ and [JSON schema](resources/environment-inventory/schema-v1.json). No importer i ## Microsoft 365 deployment -See [Office365-Deployment.md](docs/Office365-Deployment.md) for the Syncro dropdowns and clean deployment workflow. Upload the shim in `rmm/Install-MicrosoftOffice365.ps1`; publish the core installer and `resources/office/Office-UserCleanup.ps1` together first. The shim uses the existing `Tools.ps1` unchanged; deployment, host relaunch, and result handling live in the main repository script. `ValidateBeforeChanges` defaults to `true` (checks and stages media only); explicitly select `false` to enable deployment. The workload runs in Windows PowerShell 5.1, requires an explicit subscription selection, removes Office and its companion apps, preserves Windows work-account sign-in, and installs the matching suite silently using Microsoft's current ODT. It then installs new Outlook and per-machine OneDrive using Microsoft's signed installers, plus current Teams only when the selected subscription includes Teams. Pending per-user cleanup is reported separately and protects the reinstalled apps. Action/error diagnostics use the existing Tools log; the result is printed to Syncro. +See [Office365-Deployment.md](docs/Office365-Deployment.md) for the Syncro dropdowns and clean deployment workflow. Upload the shim in `rmm/Install-MicrosoftOffice365.ps1`; publish the core installer and `resources/office/Office-UserCleanup.ps1` together first. The shim uses the existing `Tools.ps1` unchanged; deployment, host relaunch, and result handling live in the main repository script. `ValidateBeforeChanges` defaults to `true` (assessment and HTTP HEAD checks without staging or downloads); explicitly select `false` to enable deployment. The workload runs in Windows PowerShell 5.1, requires an explicit subscription selection, removes Office and its companion apps, preserves Windows work-account sign-in, and installs the matching suite silently using Microsoft's current ODT. Confirmed removal corruption or residual state can trigger one Microsoft Get Help scrub before installation; its downloads are fresh and cleaned afterward, and a child window may appear. It then installs new Outlook and per-machine OneDrive using Microsoft's signed installers, plus current Teams only when the selected subscription includes Teams. Pending per-user cleanup is reported separately and protects the reinstalled apps. Action/error diagnostics use the existing Tools log; the result is printed to Syncro. ## OneDrive folder preparation diff --git a/docs/Office365-Deployment.md b/docs/Office365-Deployment.md index 5de4753..500eb47 100644 --- a/docs/Office365-Deployment.md +++ b/docs/Office365-Deployment.md @@ -62,7 +62,7 @@ Business Basic, E1, frontline/web-only plans, education/government variants, con With `ValidateBeforeChanges=true`, the script checks the subscription/activation combination, host and OS prerequisites, running apps, registered profile availability, free space, writable paths, and HTTP availability. It returns `ValidationPassed` with the deployment plan, existing Office inventory, Click-to-Run state, running apps, `WritablePaths` and `DownloadChecks`. It creates no deployment directory and downloads no response bodies, release metadata or installation files. It does not clean old artifacts, close apps, uninstall, clear credentials, register tasks, or install apps. `OfficeAppShutdown=Force` only reports running apps; `Abort` fails if any are running. -Assessment sends HTTP HEAD requests, follows redirects, and requires status 200 for the ODT discovery page, helper, selected channel's Office CDN manifest, selected companion installer links, and Windows 10 release-history page when applicable. A refused HEAD request fails assessment; there is no GET fallback. The current versioned ODT executable URL and exact Windows 10 build require reading metadata, so those are resolved only in deployment mode. `OfficeVersion` is empty, `MetadataResolved=false`, `Workspace` is null and `MediaDownloaded=false`. HEAD success does not prove payload integrity, future installation or activation. The normal Tools/core bootstrap still loads live, and the normal Tools log is written. Writable-path checks create a zero-byte delete-on-close probe in the nearest existing parent of staging, ProgramData state, and Program Files paths; they leave no probe or deployment folder behind. +Assessment sends HTTP HEAD requests, follows redirects, and requires status 200 for the ODT discovery page, helper, conditional Get Help recovery download, selected channel's Office CDN manifest, selected companion installer links, and Windows 10 release-history page when applicable. A refused HEAD request fails assessment; there is no GET fallback. The current versioned ODT executable URL and exact Windows 10 build require reading metadata, so those are resolved only in deployment mode. `OfficeVersion` is empty, `MetadataResolved=false`, `Workspace` is null and `MediaDownloaded=false`. HEAD success does not prove payload integrity, future installation or activation. The normal Tools/core bootstrap still loads live, and the normal Tools log is written. Writable-path checks create a zero-byte delete-on-close probe in the nearest existing parent of staging, ProgramData state, and Program Files paths; they leave no probe or deployment folder behind. With `ValidateBeforeChanges=false`, the script checks prerequisites, retires previous idle user cleanup tasks, removes previous deployment artifacts while preserving logs, checks available space, and creates a fresh protected workspace. It downloads and verifies the full Office payload and selected bootstrappers, rechecks free space and running apps, performs removal/installation, verifies results, and removes all non-log staging files in `finally`. Download failures occur before installed apps are removed. An active prior installer/task or unsafe/locked artifact stops preparation; cached content is never a fallback. @@ -70,7 +70,7 @@ Disk-space checks reserve **10 GB for installation and companion apps**, plus ** The script resolves the current versioned ODT download from the [Microsoft Download Center](https://www.microsoft.com/en-us/download/details.aspx?id=49117). It does not depend on the Emberkom-hosted setup.exe or a frozen Microsoft binary URL. If the page format changes, it stops before removal. The downloaded ODT package and extracted setup.exe must have valid Microsoft signatures. -**Unattended deployment does not download or launch Get Help.** The Get Help build observed on October 14, 2026 created an elevated PowerShell cleanup window in the logged-in user's session even when its parent ran hidden under SYSTEM. Hiding the parent did not hide that child, and Microsoft's documented `-HideProgress` option applies to other scenarios, not Office removal. See the [Get Help command-line reference](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-command-line-overview). The script uses ODT's supported silent removal instead; an interactive scrub is an attended troubleshooting step only. +**ODT remains the normal removal path. Get Help is downloaded and run only for conditional recovery.** The command-line scrub is noninteractive, but it is not guaranteed to be invisible: the Get Help build observed on October 14, 2026 created an elevated PowerShell cleanup window in the logged-in user's session even with a hidden SYSTEM parent. Microsoft's documented `-HideProgress` option applies to other scenarios, not Office removal, so the script does not add it. See the [Get Help command-line reference](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-command-line-overview). Normal successful deployments and assessment runs do not download the scrubber. On Windows 11, the download and installation XML omit `Version`, letting ODT select the latest available build in the selected channel. ODT may fetch newer files at installation time if the channel advances during the run. Verification accepts the staged build or a newer build and reports the actual installed version. There is no fixed build number to maintain. @@ -99,13 +99,23 @@ Shutdown detection includes `Teams.exe`, `msteams.exe` (older personal/Windows C Removal starts with the separate targeted Appx/provisioned-package and Teams/OneDrive uninstall operations. ODT then runs `setup.exe /configure remove.xml` with `` and `` to remove Click-to-Run Office, Visio, and Project without installation UI. The XML honors `OfficeAppShutdown`; `Abort` does not silently become `Force`. The script waits for setup to exit and verifies that non-MSI Office registrations disappear, allowing up to five minutes for registration changes. It also runs this pass when a Click-to-Run service or registry state remains without a finished product registration, as happens after an interrupted installation. Only a host with no non-MSI Office registration and no Click-to-Run service/state skips it. See the [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options). -Before installation, a separate read-only registry check waits for previous Click-to-Run working-configuration markers and references to Emberkom staging paths to disappear. Remaining state or unreadable state stops installation and reports an attended repair/scrub step. Deleting staging files or rebooting alone does not prove that Click-to-Run forgot an unfinished deployment. The script does not delete Microsoft's servicing registry or cache to force this check to pass; the guard is evidence of known stale state, not a guarantee about every internal Office cache. +Before installation, a read-only registry check waits for previous Click-to-Run working-configuration markers and references to Emberkom staging paths to disappear. Residual state after ODT reports success can select the single scrub recovery described below. Unreadable state stops the deployment. Deleting staging files or rebooting alone does not prove that Click-to-Run forgot an unfinished deployment. The script does not delete Microsoft's servicing registry or cache itself to force this check to pass; the guard is evidence of known stale state, not a guarantee about every internal Office cache. Legacy MSI Office is handled by `` in `install.xml`: ODT removes those products before installing the replacement suite in the same operation. Microsoft's [RemoveMSI guidance](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/upgrade-from-msi-version) covers Office, Visio, and Project 2007/2010/2013/2016. The script does not assume that a standalone `RemoveMSI` configuration without an installation is supported. Consequently, MSI Office can still be present during our identity/user-cleanup phase. After ODT finishes installation, the script verifies that detected MSI Office registrations are gone and the requested new product/version is installed. A completed MSI migration reports `3010` because a restart is required to finish removal, even if ODT returns zero. -This is a supported uninstall and reinstall with our targeted Office identity cleanup, rather than a deep scrub of every Office artifact. A failed ODT removal or remaining non-MSI Office stops before replacement installation; remaining MSI Office after `RemoveMSI` fails the deployment even if the new suite has already installed. The error reports the remaining products and links to [Microsoft's attended scrub guidance](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall). Get Help is never an automatic fallback. Corrupt, unsupported, orphaned, or unusually packaged installations may require that repair. A removal restart result follows `DeferReboot` as described above; no automatic reboot or resume task is created. A deployment already running an older script continues using that downloaded code: let it finish before starting a new deployment. +Automatic recovery is limited to **one Get Help Office scrub per deployment**, before replacement installation begins. It is selected only for these conditions: -The former Get Help 30-minute background-wait cutoff has been removed with the scrubber. Native installer processes, including ODT download/removal/installation, are awaited until they exit; there is no separate 30-minute installer cutoff. Syncro's two-hour limit remains the overall limit and is not reset between phases. Main-script registration checks now allow five minutes instead of one. Waiting for active user cleanup and its reinstall-transition lock allows 20 minutes instead of five; the per-user scheduled task limit is 30 minutes instead of 15. Those tasks may also run later for absent users. These allowances improve tolerance for slow operations but 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. +- ODT removal exits `17002` or `17004`, and a native log entry timestamped during that attempt identifies `InvalidDirectory` in `REMOVEINSTALLATION` (including the observed missing `root\integration` error). Historical entries, generic exit-code wrappers and download failures do not qualify. +- 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. + +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. Transient failures get bounded recovery before deployment stops: @@ -173,7 +183,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. Existing checks cover strings through the real shim/Tools loader, exit-code propagation, native-host relaunch, deployment order, removal/restart outcomes, 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, 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/rmm/Install-MicrosoftOffice365.ps1 b/rmm/Install-MicrosoftOffice365.ps1 index cd08707..b03bf40 100644 --- a/rmm/Install-MicrosoftOffice365.ps1 +++ b/rmm/Install-MicrosoftOffice365.ps1 @@ -6,6 +6,8 @@ # [string]$ValidateBeforeChanges - true (default: validate only), false (remove/reinstall) # Assessment checks writable paths and HTTP HEAD 200; it creates no deployment directory or downloads. # 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. # 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 8cabb31..a99805f 100644 --- a/tests/Install-MicrosoftOffice365.Tests.ps1 +++ b/tests/Install-MicrosoftOffice365.Tests.ps1 @@ -389,7 +389,7 @@ try { Assert-OfficeTest (($script:mediaProcesses -join ',') -eq 'odt.exe,setup.exe,setup.exe') 'Staging must only extract ODT and download Office, with no removal or installation.' $removal = [xml](Get-Content -LiteralPath $media.RemovalConfig -Raw) Assert-OfficeTest ($removal.Configuration.Remove.All -eq 'TRUE' -and $removal.Configuration.Display.Level -eq 'None') 'Staging must save the silent removal configuration.' - Assert-OfficeTest (!$media.Scrubber -and !($script:mediaSignatures -match 'GetHelp|SaRA')) 'Unattended deployments must not stage an interactive scrubber.' + Assert-OfficeTest (!$media.Scrubber -and !($script:mediaSignatures -match 'GetHelp|SaRA')) 'Ordinary media staging must not download the conditional scrubber.' foreach ($mode in @('win10', 'incompatible-download', 'history-unavailable')) { $mediaWorkspace = Join-Path $testRoot $mode; $null = [IO.Directory]::CreateDirectory($mediaWorkspace) $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Standard'; OfficeArchitecture='64'} @@ -553,7 +553,9 @@ try { [pscustomobject]@{DisplayName='Microsoft Office Home and Business 2021 - en-us'} } } - function Get-OfficeClickToRunState { [pscustomobject]@{Present=($script:removalMode -eq 'orphan')} } + function Get-OfficeClickToRunState { [pscustomobject]@{Present=($script:removalMode -eq 'orphan');SourceReferences=@();WorkingConfiguration=@($(if ($script:removalMode -eq 'stale') {'old-guid'}))} } + function Get-OfficeRemovalCorruptionEvidence { if ($script:removalMode -eq 'corrupt') { [pscustomobject]@{Path='fixture.log';Detail='REMOVEINSTALLATION InvalidDirectory'} } } + function Invoke-OfficeScrubRecovery { param($Media,$Workspace,$Reason) $script:scrubCalls++; Assert-OfficeTest (![string]::IsNullOrWhiteSpace($Reason)) 'Recovery must record its reason.'; return 3010 } function Invoke-OfficeProcess { param($FilePath,$Arguments,$LogPrefix) $script:removalCalls++; $script:removalStarted=$true @@ -564,25 +566,26 @@ try { $removalPath = Join-Path $testRoot 'remove [literal].xml' (New-OfficeRemovalConfiguration ([pscustomobject]@{OfficeAppShutdown='Force'})).Save($removalPath) $media = [pscustomobject]@{Setup='inert-setup.exe'; RemovalConfig=$removalPath} - foreach ($script:removalMode in @('empty','orphan','msi-only','mixed','delayed','remaining','read-error','fatal','reboot')) { - $script:removalChecks=0; $script:removalCalls=0; $script:removalStarted=$false - $script:removalCode = switch ($script:removalMode) { 'fatal' {1603}; 'reboot' {3010}; default {0} } + foreach ($script:removalMode in @('empty','orphan','msi-only','mixed','delayed','remaining','stale','corrupt','unknown-17004','read-error','fatal','reboot')) { + $script:removalChecks=0; $script:removalCalls=0; $script:removalStarted=$false; $script:scrubCalls=0 + $script:removalCode = switch ($script:removalMode) { 'fatal' {1603}; 'reboot' {3010}; 'corrupt' {17004}; 'unknown-17004' {17004}; default {0} } if ($script:removalMode -eq 'remaining') { - Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'Office remains.*Office Home and Business 2021.*manual scrub' + Assert-OfficeTest ((Remove-OfficeSuite $media $testRoot) -eq 3010) 'Verified leftovers after ODT success must select scrub recovery.' Assert-OfficeTest ($script:removalChecks -eq ((Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts + 2)) 'Remaining Click-to-Run products must be checked for the bounded registration interval.' } elseif ($script:removalMode -eq 'read-error') { Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'Office inventory is unreadable' - } elseif ($script:removalMode -eq 'fatal') { - Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'ODT Office removal failed \(exit 1603\).*No interactive scrubber was launched.*manual scrub' + } elseif ($script:removalMode -in @('fatal','unknown-17004')) { + Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'ODT Office removal failed.*automatic scrub was not selected' } else { $result = @(Remove-OfficeSuite $media $testRoot) - $expected = if ($script:removalMode -eq 'reboot') {3010} else {0} + $expected = if ($script:removalMode -in @('reboot','corrupt','stale')) {3010} else {0} Assert-OfficeTest ($result.Count -eq 1 -and $result[0] -eq $expected) 'Removal must return just its exit code; MSI products are deferred to installation.' if ($script:removalMode -eq 'delayed') { Assert-OfficeTest ($script:removalChecks -eq 4) 'Removal must tolerate registry propagation delays.' } if ($script:removalMode -eq 'reboot') { Assert-OfficeTest ($script:removalChecks -eq 1) 'A required restart must be surfaced before demanding registration cleanup.' } } $expectedCalls = if ($script:removalMode -in @('empty','msi-only')) {0} else {1} - Assert-OfficeTest ($script:removalCalls -eq $expectedCalls) 'Remove orphaned Click-to-Run state even without registered products, without rerunning failed removal or launching a fallback scrubber.' + Assert-OfficeTest ($script:removalCalls -eq $expectedCalls) 'Remove orphaned Click-to-Run state even without registered products, without rerunning ODT.' + Assert-OfficeTest ($script:scrubCalls -eq $(if ($script:removalMode -in @('corrupt','remaining','stale')) {1} else {0})) 'Only confirmed removal corruption or leftovers may trigger a single scrub.' } } & { @@ -834,6 +837,123 @@ try { Assert-OfficeTest ((Get-Content -LiteralPath $Global:LogFile -Raw) -match 'Error: User cleanup task registration failed for unmapped \(C:\\Users\\defaultuser100000\)') 'Registration failures must reach the Tools diagnostic log.' } + # Classify only current, removal-specific corruption; stale errors in a live + # service log and generic 17004 wrappers must not authorize a destructive scrub. + & { + $path=Join-Path $testRoot 'Office-corruption.log' + function Get-OfficeSetupLogFiles { Get-Item -LiteralPath $path } + $since=[DateTime]::UtcNow.AddSeconds(-2) + $stamp=[DateTime]::Now.ToString('M/d/yyyy H:mm:ss.fff', [Globalization.CultureInfo]::InvariantCulture) + $detail='OFFICECL Click-To-Run Non Task Error {"ErrorCode":30034,"ErrorType":"InvalidDirectory","ErrorMessage":"GetFiles: search path root\\integration does not exist","Task":"REMOVEINSTALLATION:{A1D863B9-4F69-45AF-BD5C-D349E5C0C851}"}' + Set-Content -LiteralPath $path -Value "$stamp`t$detail" + $evidence=Get-OfficeRemovalCorruptionEvidence $since + Assert-OfficeTest ($evidence.Path -eq $path -and $evidence.Detail.Contains('root\\integration')) 'The observed InvalidDirectory removal error must trigger recovery evidence.' + foreach ($line in @( + ('10/22/2026 13:57:00.000' + "`t" + $detail), + ("$stamp`t" + $detail.Replace('REMOVEINSTALLATION', 'INSTALL')), + ("$stamp`t" + $detail.Replace('InvalidDirectory', 'AccessDenied')), + ("$stamp`tSETUP unknown error [ExitCode=17004]"), + ('No timestamp ' + $detail), + ([DateTime]::Now.AddHours(1).ToString('M/d/yyyy H:mm:ss.fff', [Globalization.CultureInfo]::InvariantCulture) + "`t" + $detail) + )) { + Set-Content -LiteralPath $path -Value $line + Assert-OfficeTest ($null -eq (Get-OfficeRemovalCorruptionEvidence $since)) 'Old, unrelated, unparseable and future evidence must not select recovery.' + } + function Get-Content { throw 'Log locked' } + Assert-OfficeTest ($null -eq (Get-OfficeRemovalCorruptionEvidence $since)) 'Unreadable evidence must not select recovery.' + } + # Download/extract only on demand, validate the Microsoft executable, and never + # rely on Tools.ps1's shadowed Expand-Archive or a previously extracted package. + & { + Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem + $script:scrubPackageMode='single'; $script:scrubSignatures=@(); $script:scrubDownloads=0 + function Save-OfficeDownload { + param($Uri,$Path) + Assert-OfficeTest ($Uri -eq (Get-OfficeDeploymentDefinitions).GetHelpUrl) 'Recovery must use the current Microsoft download link.' + $script:scrubDownloads++ + $zip=[IO.Compression.ZipFile]::Open($Path, [IO.Compression.ZipArchiveMode]::Create) + try { + $entries = switch ($script:scrubPackageMode) { + 'traversal' { @('../escaped.exe') } + 'missing' { @('readme.txt') } + 'duplicate' { @('one/GetHelpCmd.exe','two/GetHelpCmd.exe') } + default { @('GetHelpCmd.exe','support.dll') } + } + foreach ($name in $entries) { $entry=$zip.CreateEntry($name); $writer=[IO.StreamWriter]::new($entry.Open()); try { $writer.Write('Inert archive fixture, never executed.') } finally { $writer.Dispose() } } + } finally { $zip.Dispose() } + } + function Assert-OfficeMicrosoftSignature { param($Path) $script:scrubSignatures += $Path; if ($script:scrubPackageMode -eq 'unsigned') { throw 'Invalid Microsoft signature' } } + function Expand-Archive { throw 'Must use the literal-path Archive module, not the Tools override.' } + foreach ($script:scrubPackageMode in @('single','missing','duplicate','traversal','unsigned')) { + $workspace=Join-Path $testRoot ('scrub package [' + $script:scrubPackageMode + ']'); $null=[IO.Directory]::CreateDirectory($workspace) + if ($script:scrubPackageMode -eq 'single') { + $exe=Initialize-OfficeScrubMedia $workspace + Assert-OfficeTest ($exe -eq (Join-Path $workspace 'GetHelp\GetHelpCmd.exe') -and $exe -in $script:scrubSignatures) 'Freshly extracted Get Help must pass signature verification.' + $before=$script:scrubDownloads + Assert-OfficeThrows { Initialize-OfficeScrubMedia $workspace } 'refusing to reuse' + Assert-OfficeTest ($script:scrubDownloads -eq $before) 'A second recovery must not download or reuse its package.' + } elseif ($script:scrubPackageMode -eq 'traversal') { + Assert-OfficeThrows { Initialize-OfficeScrubMedia $workspace } 'outside the Office deployment root' + Assert-OfficeTest (!(Test-Path -LiteralPath (Join-Path $workspace 'escaped.exe'))) 'ZIP extraction must not escape its folder.' + } elseif ($script:scrubPackageMode -eq 'unsigned') { Assert-OfficeThrows { Initialize-OfficeScrubMedia $workspace } 'Invalid Microsoft signature' } + else { Assert-OfficeThrows { Initialize-OfficeScrubMedia $workspace } 'exactly one GetHelpCmd.exe' } + } + } + # A scrub requires both a successful scenario/process result and independently + # verified removal. Every attempt is bounded to one and cleanup retains its logs. + & { + $script:scrubLaunches=0 + function Initialize-OfficeScrubMedia { + param($Workspace) + Set-Content -LiteralPath (Join-Path $Workspace 'GetHelp.zip') -Value 'fixture' + if ($script:scrubMode -eq 'download') { throw 'Scrub download failed' } + Join-Path $Workspace 'GetHelpCmd.exe' + } + 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.' + Set-Content -LiteralPath "$LogPrefix.stdout.log" -Value $script:scrubOutput + Set-Content -LiteralPath "$LogPrefix.stderr.log" -Value '' + $script:scrubExit + } + function Get-CimInstance { if ($script:scrubMode -eq 'running') { [pscustomobject]@{Name='GetHelpCmd.exe'} } } + 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','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) { + 'restart' { $script:scrubExit=3010 } + 'failure' { $script:scrubOutput='09: Failure to remove Office.' } + '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='' } + 'contradictory' { $script:scrubOutput="09: Failure`n00: Success" } + 'bad-exit' { $script:scrubExit=1 } + } + if ($script:scrubMode -in @('success','restart')) { + $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'} } + 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.' } + 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.' } + } + } + 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.' + } # Deployment resolves release metadata and deletes it on success or failure. & { $script:historyPaths=@() @@ -866,11 +986,11 @@ try { function Save-OfficeDownload { throw 'Assessment must not download data.' } $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'} $checks = @(Test-OfficeDownloadLinks $options) - Assert-OfficeTest ($checks.Count -eq 6 -and $checks.Count -eq $script:heads.Count) 'HEAD checks must cover ODT discovery, helper, CDN, and selected companions.' + Assert-OfficeTest ($checks.Count -eq 7 -and $checks.Count -eq $script:heads.Count) 'HEAD checks must cover ODT discovery, helper, recovery link, CDN, and selected companions.' Assert-OfficeTest ((Get-OfficeDeploymentDefinitions).CompanionInstallers.Teams.Uri -notin $script:heads) 'No-Teams assessment must not probe the Teams download.' $options.InstallTeams=$true; $options.OfficeFeatureRelease='2608'; $script:heads=@() $checks = @(Test-OfficeDownloadLinks $options) - Assert-OfficeTest ($checks.Count -eq 8 -and (Get-OfficeDeploymentDefinitions).OfficeReleaseHistory -in $script:heads) 'Windows 10 assessment must check history availability without resolving the build.' + Assert-OfficeTest ($checks.Count -eq 9 -and (Get-OfficeDeploymentDefinitions).OfficeReleaseHistory -in $script:heads) 'Windows 10 assessment must check history availability without resolving the build.' $script:headCode=204 Assert-OfficeThrows { Test-OfficeDownloadLinks $options } 'returned 204; expected 200' $script:headFails=$true @@ -1027,11 +1147,18 @@ try { Set-Content -LiteralPath (Join-Path $profile 'NTUSER.DAT') -Value 'test hive, never loaded' function Stop-OfficeDeploymentApps { $script:events += 'apps' } function Get-OfficeRunningApps { } - function Get-OfficeSuiteInventory { if ($script:mode -ne 'office-reboot' -or $script:removalStillRegistered) { [pscustomobject]@{DisplayName='Synthetic Office'} } } + function Get-OfficeSuiteInventory { if ($script:mode -notin @('office-reboot','scrub-recovery') -or $script:removalStillRegistered) { [pscustomobject]@{DisplayName='Synthetic Office'} } } function Get-OfficeMachineCompanionEntries { if ($script:removalStillRegistered) { [pscustomobject]@{DisplayName='Synthetic OneDrive'} } } function Initialize-OfficeMedia { param($Options,$Workspace) $script:events += 'download'; if ($script:mode -in @('download','download-cleanup')) { throw 'download failure' }; [pscustomobject]@{Version='16.0.1.2'; Helper=(Join-Path $Workspace 'Office-UserCleanup.ps1')} } function Remove-OfficeCompanionApps { $script:events += 'companions'; if ($script:mode -eq 'companions') { throw 'companion failure' }; return ($script:mode -eq 'reboot') } - function Remove-OfficeSuite { $script:events += 'remove-office'; if ($script:mode -eq 'remove-office') { throw 'Office removal failure' }; if ($script:mode -eq 'office-reboot') { return 3010 }; return 0 } + function Remove-OfficeSuite { + param($Media,$Workspace) + $script:events += 'remove-office' + if ($script:mode -eq 'remove-office') { throw 'Office removal failure' } + if ($script:mode -eq 'scrub-recovery') { $Media | Add-Member ScrubAttempted $true; $Media | Add-Member ScrubReason 'fixture recovery'; return 3010 } + if ($script:mode -eq 'office-reboot') { return 3010 } + return 0 + } function Clear-OfficeProfileIdentity { $script:events += 'identity'; if ($script:mode -eq 'identity') { throw 'identity failure' } } function Start-OfficeUserCleanup { $script:events += 'user'; if ($script:mode -eq 'user') { throw 'user still running' } @@ -1063,6 +1190,14 @@ try { if ($script:mode -eq 'office-reboot') { Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'RestartRequiredBeforeInstall' -and 'identity' -notin $script:events -and 'user' -notin $script:events) 'Office removal restart must stop before user cleanup and replacement installation.' } if ($script:mode -eq 'success') { Assert-OfficeTest (($script:events -join ',') -eq 'download,apps,companions,remove-office,identity,user,phase,install,install-companions') 'Deployment order changed.' } } + foreach ($deferScrub in @('true','false')) { + $script:mode='scrub-recovery'; $script:events=@() + $options=Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium';OfficeAppShutdown='Force';ValidateBeforeChanges='false';DeferReboot=$deferScrub} + $result=Invoke-OfficeDeployment $options + Assert-OfficeTest ($result.ExitCode -eq 3010 -and $result.ScrubRecoveryAttempted -and $result.ScrubRecoveryReason -eq 'fixture recovery') 'Scrub recovery and restart requirement must be visible in the final receipt.' + if ($deferScrub -eq 'true') { Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'Installed' -and 'install' -in $script:events) 'Verified scrub may continue installation when reboot is deferred.' } + else { Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'RestartRequiredBeforeInstall' -and 'install' -notin $script:events -and 'identity' -notin $script:events) 'Nondeferred scrub restart must stop before replacement installation and user cleanup.' } + } $script:mode='preflight-space'; $script:events=@(); $options.ValidateBeforeChanges=$true; $script:workspaceCreates=0; $script:artifactCleanupRuns=0 Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Insufficient disk space before download' Assert-OfficeTest ($script:events.Count -eq 0 -and $script:workspaceCreates -eq 0 -and $script:artifactCleanupRuns -eq 0) 'Low-space validation must stop without staging or housekeeping.'