From b07e132b3c762f06cec9f2d7a9c64ad31062b66e Mon Sep 17 00:00:00 2001 From: ek-dyoder Date: Wed, 14 Oct 2026 17:33:23 -0400 Subject: [PATCH] improved resiliency during Office uninstall/install operations --- Install-MicrosoftOffice365.ps1 | 177 ++++++++++++++--- docs/Office365-Deployment.md | 18 +- resources/office/Office-UserCleanup.ps1 | 67 ++++++- tests/Install-MicrosoftOffice365.Tests.ps1 | 218 ++++++++++++++++++++- 4 files changed, 437 insertions(+), 43 deletions(-) diff --git a/Install-MicrosoftOffice365.ps1 b/Install-MicrosoftOffice365.ps1 index 0ce5bf0..b3996de 100644 --- a/Install-MicrosoftOffice365.ps1 +++ b/Install-MicrosoftOffice365.ps1 @@ -37,7 +37,7 @@ function Get-OfficeDeploymentDefinitions { ScrubScenarioPattern = '(?m)^\s*(\d{2}):' ScrubScenarioSuccess = @('00', '66', '68') ScrubExitSuccess = @(0, 66, 68) - HelperVersion = 'EmberkomOfficeUserCleanup-v2' + HelperVersion = 'EmberkomOfficeUserCleanup-v4' Language = 'en-us' OfficeBuildPattern = '^16\.0\.\d+\.\d+$' OdtExcludedApps = @('Groove', 'OneDrive', 'Lync', 'Teams', 'OutlookForWindows') @@ -68,6 +68,11 @@ function Get-OfficeDeploymentDefinitions { DownloadTimeoutSeconds = 300 DownloadRetrySeconds = 3 OdtPageTimeoutSeconds = 120 + MsiBusyAttempts = 5 + MsiBusyRetrySeconds = 15 + RegistrationCheckAttempts = 13 + RegistrationCheckSeconds = 5 + AppxRemovalAttempts = 3 UserCleanupWaitMinutes = 5 UserCleanupTaskMinutes = 15 } @@ -163,12 +168,13 @@ function Assert-OfficeMicrosoftSignature { } function Save-OfficeDownload { - param([string]$Uri, [string]$Path) + param([string]$Uri, [string]$Path, [int]$TimeoutSeconds = 0) $definitions = Get-OfficeDeploymentDefinitions + if (!$TimeoutSeconds) { $TimeoutSeconds = $definitions.DownloadTimeoutSeconds } for ($attempt = 1; $attempt -le $definitions.DownloadAttempts; $attempt++) { try { $null = Write-Output "Download attempt ${attempt}: $Uri -> $Path" - Invoke-WebRequest -UseBasicParsing -Uri $Uri -OutFile $Path -TimeoutSec $definitions.DownloadTimeoutSeconds -ErrorAction Stop + Invoke-WebRequest -UseBasicParsing -Uri $Uri -OutFile $Path -TimeoutSec $TimeoutSeconds -ErrorAction Stop if ((Get-Item -LiteralPath $Path -ErrorAction Stop).Length -eq 0) { throw 'Download was empty.' } return } catch { @@ -189,11 +195,33 @@ function Get-OfficeOdtDownloadUrl { function Invoke-OfficeProcess { param([string]$FilePath, [string]$Arguments, [string]$LogPrefix) - $null = Write-Output "Running: $FilePath $Arguments. Process logs: $LogPrefix" - $process = Start-Process -FilePath $FilePath -ArgumentList $Arguments -WorkingDirectory (Split-Path -Parent $FilePath) -Wait -PassThru -WindowStyle Hidden -RedirectStandardOutput "$LogPrefix.stdout.log" -RedirectStandardError "$LogPrefix.stderr.log" -ErrorAction Stop - if ($null -eq $process.ExitCode) { throw "No exit code returned from $FilePath." } - $null = Write-Output "Process exited $($process.ExitCode): $FilePath" - [int]$process.ExitCode + $definitions = Get-OfficeDeploymentDefinitions + $isMsi = [IO.Path]::GetFileName($FilePath) -ieq 'msiexec.exe' + for ($attempt = 1; ; $attempt++) { + $prefix = if ($attempt -eq 1) { $LogPrefix } else { "$LogPrefix.retry-$attempt" } + $null = Write-Output "Running: $FilePath $Arguments. Process logs: $prefix" + $process = Start-Process -FilePath $FilePath -ArgumentList $Arguments -WorkingDirectory (Split-Path -Parent $FilePath) -Wait -PassThru -WindowStyle Hidden -RedirectStandardOutput "$prefix.stdout.log" -RedirectStandardError "$prefix.stderr.log" -ErrorAction Stop + if ($null -eq $process.ExitCode) { throw "No exit code returned from $FilePath." } + $null = Write-Output "Process exited $($process.ExitCode): $FilePath" + # Retry only MSI's documented busy result, not arbitrary installer failures. + if (!$isMsi -or $process.ExitCode -ne 1618 -or $attempt -ge $definitions.MsiBusyAttempts) { return [int]$process.ExitCode } + $null = Write-Output "Windows Installer is busy; retrying in $($definitions.MsiBusyRetrySeconds) seconds (attempt $attempt of $($definitions.MsiBusyAttempts))." + Start-Sleep -Seconds $definitions.MsiBusyRetrySeconds + } +} + +function Wait-OfficeResult { + param([scriptblock]$Probe, [string]$Description) + # A probe returns a verified value/true, or nothing/false while registration catches up. + # Read errors still propagate; an inaccessible registry is not proof of removal. + $definitions = Get-OfficeDeploymentDefinitions + for ($attempt = 1; $attempt -le $definitions.RegistrationCheckAttempts; $attempt++) { + $value = & $Probe + if ($value) { return $value } + if ($attempt -eq $definitions.RegistrationCheckAttempts) { return } + if ($attempt -eq 1) { $null = Write-Output "Waiting for $Description (up to $(($definitions.RegistrationCheckAttempts - 1) * $definitions.RegistrationCheckSeconds) seconds)." } + Start-Sleep -Seconds $definitions.RegistrationCheckSeconds + } } function New-OfficeConfiguration { @@ -235,8 +263,9 @@ function Initialize-OfficeMedia { param($Options, [string]$Workspace) $definitions = Get-OfficeDeploymentDefinitions [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 - $page = Invoke-WebRequest -UseBasicParsing -Uri $definitions.OdtPage -TimeoutSec $definitions.OdtPageTimeoutSeconds -ErrorAction Stop - $url = Get-OfficeOdtDownloadUrl $page.Content + $pagePath = Join-Path $Workspace 'odt-download-page.html' + Save-OfficeDownload $definitions.OdtPage $pagePath -TimeoutSeconds $definitions.OdtPageTimeoutSeconds + $url = Get-OfficeOdtDownloadUrl (Get-Content -LiteralPath $pagePath -Raw -ErrorAction Stop) $package = Join-Path $Workspace 'odt.exe' $null = Write-Output "Downloading current ODT from $url" Save-OfficeDownload $url $package @@ -265,7 +294,13 @@ function Initialize-OfficeMedia { $configPath = Join-Path $Workspace 'install.xml' $config = New-OfficeConfiguration $Options $odtFolder; $config.Save($configPath) $null = Write-Output 'Downloading Office installation files before removing installed apps.' - $code = Invoke-OfficeProcess $setup "/download `"$configPath`"" (Join-Path $Workspace 'office-download') + for ($attempt = 1; $attempt -le $definitions.DownloadAttempts; $attempt++) { + $prefix = if ($attempt -eq 1) { 'office-download' } else { "office-download.retry-$attempt" } + $code = Invoke-OfficeProcess $setup "/download `"$configPath`"" (Join-Path $Workspace $prefix) + if ($code -eq 0 -or $attempt -eq $definitions.DownloadAttempts) { break } + $null = Write-Output "Office download failed ($code); retrying download into the same staging folder (attempt $attempt of $($definitions.DownloadAttempts))." + Start-Sleep -Seconds ($definitions.DownloadRetrySeconds * $attempt) + } if ($code -ne 0) { throw "Office download failed ($code). Existing Office has not been removed." } $versions = @(Get-ChildItem -LiteralPath (Join-Path $odtFolder 'Office\Data') -Directory -ErrorAction Stop | Where-Object { $_.Name -match $definitions.OfficeBuildPattern }) if ($versions.Count -ne 1) { throw 'Office download did not produce one identifiable build.' } @@ -288,7 +323,13 @@ function Stop-OfficeDeploymentApps { if (!$running.Count) { return } if ($Options.OfficeAppShutdown -ne 'Force') { throw "Apps are running: $(($running.ProcessName | Sort-Object -Unique) -join ', '). Close them or select OfficeAppShutdown=Force (unsaved work can be lost)." } $null = Write-Output 'Closing Office, Teams, OneDrive, and new Outlook in every session. Unsaved work can be lost.' - $running | Stop-Process -Force -ErrorAction Stop + foreach ($process in $running) { + try { Stop-Process -InputObject $process -Force -ErrorAction Stop } + catch { + if (!$process.HasExited) { throw } + $null = Write-Output "Process $($process.Id) exited before it could be stopped; continuing." + } + } } function Get-OfficeCompanionDownloads { @@ -348,7 +389,7 @@ function Install-OfficeCompanionApps { $code = Invoke-OfficeProcess $Media.WebView2 $definitions.CompanionInstallers.WebView2.Arguments (Join-Path $Workspace 'webview2-install') if ($code -notin @(0, 3010)) { throw "WebView2 installation failed (exit $code)." } if ($code -eq 3010) { $reboot = $true } - $webViewVersion = Get-OfficeMachineWebViewVersion + $webViewVersion = Wait-OfficeResult { Get-OfficeMachineWebViewVersion } 'machine WebView2 registration' if (!$webViewVersion) { throw 'WebView2 setup returned success but no machine-wide runtime was detected.' } } $versions = [ordered]@{ WebView2=$webViewVersion } @@ -362,11 +403,11 @@ function Install-OfficeCompanionApps { if ($code -notin @(0, 3010)) { throw "$($app.Name) installation failed (exit $code). See logs in $Workspace." } if ($code -eq 3010) { $reboot = $true } if ($app.Package) { - $packages = @(Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.DisplayName -eq $app.Package -and $_.PackageName -like ('*' + $definitions.AppxPublisherSuffix) }) + $packages = @(Wait-OfficeResult { Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.DisplayName -eq $app.Package -and $_.PackageName -like ('*' + $definitions.AppxPublisherSuffix) } } "$($app.Name) provisioning") if (!$packages.Count) { throw "$($app.Name) setup returned success but the app was not provisioned for all users." } $versions[$app.Name] = ($packages.Version | Sort-Object -Unique) -join ', ' } else { - $oneDrive = Get-OfficeMachineOneDrive + $oneDrive = Wait-OfficeResult { Get-OfficeMachineOneDrive } 'per-machine OneDrive registration' if (!$oneDrive) { throw 'OneDrive setup returned success but a per-machine installation was not detected.' } Assert-OfficeMicrosoftSignature $oneDrive.Path $versions.OneDrive = $oneDrive.Version @@ -422,6 +463,8 @@ function Remove-OfficeSuite { $prefix = Join-Path $Workspace 'office-scrub' $code = Invoke-OfficeProcess $Media.Scrubber (Get-OfficeDeploymentDefinitions).ScrubArguments $prefix $output = (Get-Content -LiteralPath "$prefix.stdout.log" -Raw -ErrorAction Stop) + (Get-Content -LiteralPath "$prefix.stderr.log" -Raw -ErrorAction Stop) + Assert-OfficeScrubResult $code $output @() + $null = Wait-OfficeResult { @(Get-OfficeSuiteInventory).Count -eq 0 } 'Office removal registration' Assert-OfficeScrubResult $code $output @(Get-OfficeSuiteInventory) } @@ -443,25 +486,93 @@ function Get-OfficeOneDriveCommand { [pscustomobject]@{ FilePath = $exe; Arguments = $arguments } } +function Test-OfficeMachineMsiProduct { + param([Parameter(Mandatory=$true)][ValidatePattern('^\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\}$')][string]$ProductCode) + if (!('Emberkom.OfficeMachineMsi' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +namespace Emberkom { + public static class OfficeMachineMsi { + [DllImport("msi.dll", CharSet=CharSet.Unicode, ExactSpelling=true)] + private static extern uint MsiEnumProductsExW(string product, string userSid, uint context, uint index, IntPtr code, IntPtr installedContext, IntPtr sid, IntPtr sidLength); + public static uint Find(string product) { + // MSIINSTALLCONTEXT_MACHINE requires a native NULL user SID. + return MsiEnumProductsExW(product, null, 4, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); + } + } +} +'@ + } + # Read-only MSI enumeration avoids Win32_Product and its repair side effects. + $code = [Emberkom.OfficeMachineMsi]::Find($ProductCode) + if ($code -eq 0) { return $true } + if ($code -in @(259, 1605)) { return $false } + throw "Cannot determine machine MSI registration for $ProductCode (Win32 $code)." +} + +function Get-OfficeMachineCompanionEntries { + $definitions = Get-OfficeDeploymentDefinitions + foreach ($entry in @(Get-OfficeUninstallEntries)) { + if ($entry.DisplayName -notin (@('Microsoft OneDrive') + $definitions.TeamsMsiNames)) { continue } + if ($entry.DisplayName -eq 'Microsoft Teams Meeting Add-in for Microsoft Office' -and !(Test-OfficeMachineMsiProduct $entry.PSChildName)) { + # Some per-user add-ins advertise themselves in HKLM. Their registration alone + # does not mean SYSTEM can uninstall them. The user helper checks both hives. + $null = Write-Output "No machine MSI registration for $($entry.DisplayName) $($entry.DisplayVersion), $($entry.PSChildName). Per-user registration will be checked by user cleanup. Registry entry: $($entry.PSPath)" + continue + } + $entry + } +} + +function Remove-OfficeAppxEntry { + param([string]$PackageName, [switch]$Provisioned) + $definitions = Get-OfficeDeploymentDefinitions + for ($attempt = 1; $attempt -le $definitions.AppxRemovalAttempts; $attempt++) { + $null = Write-Output "Removing Appx package $PackageName (provisioned=$Provisioned, attempt $attempt)." + try { + if ($Provisioned) { $null = Remove-AppxProvisionedPackage -Online -PackageName $PackageName -AllUsers -ErrorAction Stop } + else { Remove-AppxPackage -Package $PackageName -AllUsers -ErrorAction Stop } + } catch { + # Another removal can already have removed this registration. Verify before failing. + $null = Write-Output "Appx removal reported an error for ${PackageName}: $($_.Exception.Message). Checking state before retrying." + } + $gone = Wait-OfficeResult { + $registered = @(if ($Provisioned) { + Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.PackageName -eq $PackageName } + } else { + Get-AppxPackage -AllUsers -ErrorAction Stop | Where-Object { $_.PackageFullName -eq $PackageName } + }) + $registered.Count -eq 0 + } "removal of $PackageName" + if ($gone) { return } + } + throw "Appx package remains after $($definitions.AppxRemovalAttempts) removal attempts: $PackageName. Check the diagnostic log." +} + function Remove-OfficeCompanionApps { param([string]$Workspace) $names = Get-OfficeAppxNames $definitions = Get-OfficeDeploymentDefinitions foreach ($package in @(Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.DisplayName -in $names })) { - $null = Write-Output "Removing provisioned package: $($package.PackageName)" - $null = Remove-AppxProvisionedPackage -Online -PackageName $package.PackageName -AllUsers -ErrorAction Stop + Remove-OfficeAppxEntry $package.PackageName -Provisioned } foreach ($package in @(Get-AppxPackage -AllUsers -ErrorAction Stop | Where-Object { $_.Name -in $names })) { - $null = Write-Output "Removing installed package: $($package.PackageFullName)" - Remove-AppxPackage -Package $package.PackageFullName -AllUsers -ErrorAction Stop + Remove-OfficeAppxEntry $package.PackageFullName } - if (@(Get-AppxPackage -AllUsers -ErrorAction Stop | Where-Object { $_.Name -in $names }).Count) { throw 'Office/Teams/Outlook Store packages remain after removal.' } + $gone = Wait-OfficeResult { + $installed = @(Get-AppxPackage -AllUsers -ErrorAction Stop | Where-Object { $_.Name -in $names }) + $provisioned = @(Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.DisplayName -in $names }) + ($installed.Count + $provisioned.Count) -eq 0 + } 'Office/Teams/Outlook Store package removal' + if (!$gone) { throw 'Office/Teams/Outlook Store packages remain after removal.' } $reboot = $false - foreach ($entry in @(Get-OfficeUninstallEntries)) { + foreach ($entry in @(Get-OfficeMachineCompanionEntries)) { + $null = Write-Output "Removing machine companion: $($entry.DisplayName) $($entry.DisplayVersion). Registry entry: $($entry.PSPath)" if ($entry.DisplayName -in $definitions.TeamsMsiNames) { if ($entry.PSChildName -notmatch '^\{[0-9A-Fa-f-]{36}\}$') { throw 'Teams MSI has an unexpected product code.' } $prefix = Join-Path $Workspace ('teams-' + $entry.PSChildName) - $code = Invoke-OfficeProcess "$env:WINDIR\System32\msiexec.exe" "/x $($entry.PSChildName) /qn /norestart /L*v `"$prefix.log`"" $prefix + $code = Invoke-OfficeProcess "$env:WINDIR\System32\msiexec.exe" "/x $($entry.PSChildName) /qn /norestart /L+*v `"$prefix.log`"" $prefix } elseif ($entry.DisplayName -eq 'Microsoft OneDrive') { $roots = @((Join-Path $env:ProgramFiles 'Microsoft OneDrive'), (Join-Path $env:WINDIR 'System32'), (Join-Path $env:WINDIR 'SysWOW64')) if (${env:ProgramFiles(x86)}) { $roots += Join-Path ${env:ProgramFiles(x86)} 'Microsoft OneDrive' } @@ -472,7 +583,13 @@ function Remove-OfficeCompanionApps { if ($code -eq 3010) { $reboot = $true } elseif ($code -notin @(0, 1605, 1614)) { throw "Could not remove $($entry.DisplayName) (exit $code)." } } - if (@(Get-OfficeUninstallEntries | Where-Object { $_.DisplayName -in (@('Microsoft OneDrive') + $definitions.TeamsMsiNames) }).Count -and !$reboot) { throw 'A machine-wide Teams/OneDrive installation remains after removal.' } + if (!$reboot) { $null = Wait-OfficeResult { @(Get-OfficeMachineCompanionEntries).Count -eq 0 } 'machine companion removal registration' } + $remaining = @(Get-OfficeMachineCompanionEntries) + if ($remaining.Count) { + $details = ($remaining | ForEach-Object { "$($_.DisplayName) $($_.DisplayVersion) [$($_.PSPath)]" }) -join '; ' + $null = Write-Output "Machine companion registrations remaining after removal: $details" + if (!$reboot) { throw "Machine companion registrations remain after removal: $details. Check uninstall logs in $Workspace. Office scrub/installation has not started." } + } $reboot } @@ -547,7 +664,10 @@ function Start-OfficeUserCleanup { $pending = @() foreach ($task in $tasks) { $marker = Get-ItemPropertyValue -LiteralPath "Registry::HKEY_USERS\$($task.SID)\Software\Emberkom\OfficeDeployment\$deploymentId" -Name Status -ErrorAction SilentlyContinue - if ($marker -eq 'Complete') { Unregister-ScheduledTask -TaskName $task.Name -Confirm:$false -ErrorAction Stop } + if ($marker -eq 'Complete') { + try { Unregister-ScheduledTask -TaskName $task.Name -Confirm:$false -ErrorAction Stop } + catch { $null = Write-Output "Cleanup completed, but its task could not be unregistered: $($task.Name). The Complete marker makes it a no-op. $($_.Exception.Message)" } + } else { $pending += $task.SID; $null = Write-Output "Cleanup pending for $($task.SID); task $($task.Name) runs at their next sign-in." } } return ,$pending @@ -557,9 +677,14 @@ function Install-OfficeMedia { param($Options, $Media, [string]$Workspace) $code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.Config)`"" (Join-Path $Workspace 'office-install') if ($code -notin @(0, 3010)) { throw "Office installation failed (exit $code). Media and logs remain in $Workspace." } - $installed = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration' -ErrorAction Stop $platform = if ($Options.OfficeArchitecture -eq '64') { 'x64' } else { 'x86' } - if ($Options.ProductId -notin ($installed.ProductReleaseIds -split ',') -or $installed.Platform -ne $platform -or $installed.VersionToReport -ne $Media.Version) { throw 'Setup exited successfully but the installed product, architecture, or version did not match.' } + $verified = Wait-OfficeResult { + $key = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration' + if (!(Test-Path -LiteralPath $key -ErrorAction Stop)) { return $false } + $installed = Get-ItemProperty -LiteralPath $key -ErrorAction Stop + $Options.ProductId -in ($installed.ProductReleaseIds -split ',') -and $installed.Platform -eq $platform -and $installed.VersionToReport -eq $Media.Version + } 'the selected Office product, architecture, and version' + if (!$verified) { throw 'Setup exited successfully but the installed product, architecture, or version did not match.' } $code } diff --git a/docs/Office365-Deployment.md b/docs/Office365-Deployment.md index 32bee22..194f755 100644 --- a/docs/Office365-Deployment.md +++ b/docs/Office365-Deployment.md @@ -6,7 +6,7 @@ The selection identifies the client's purchased subscription; it does not discov ## Publish and configure -1. Publish `Install-MicrosoftOffice365.ps1` and `resources/office/Office-UserCleanup.ps1` together in the public repository. The installer requires helper version `EmberkomOfficeUserCleanup-v2`, which protects reinstalled apps from deferred cleanup. The existing `Tools.ps1` is used unchanged. Nothing in this change publishes itself. +1. Publish `Install-MicrosoftOffice365.ps1` and `resources/office/Office-UserCleanup.ps1` together in the public repository. The installer requires helper version `EmberkomOfficeUserCleanup-v3`, which handles per-user Teams add-ins advertised in HKLM and protects reinstalled apps from deferred cleanup. The existing `Tools.ps1` is used unchanged. Nothing in this change publishes itself. 2. Paste/upload **rmm/Install-MicrosoftOffice365.ps1** as the Syncro **Windows PowerShell 5.1** script. Select **Run As: System**. PowerShell 7 is not required or launched. Allow a generous maximum runtime, initially 180 minutes, and enough disk space for both the download and installation. A clean deployment downloads several GB per endpoint and requires internet access throughout companion app installation. 3. Use **Add Script Variable**, type **Dropdown**, then **Edit Dropdown Values** for each variable below. Enter names without `$`. Syncro stores dropdown definitions separately; uploading a `.ps1` does not create them. See [Syncro's script editor documentation](https://docs.syncrosecure.com/scripting-apis/manage-scripts). 4. First run with `ValidateBeforeChanges=true` and review the result. To deploy, rerun with `false` during the maintenance window. Pilot on a disposable VM with representative Office, user profiles, and companion apps. Then run against the intended endpoint or asset selection. Group endpoints by subscription and architecture so each run's selections apply correctly. @@ -82,12 +82,24 @@ New Outlook, and Teams when selected, are provisioned for current and future use Removal uses [Get Help's OfficeScrubScenario](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall) with `-OfficeVersion All`, plus separate targeted Appx/provisioned-package and Teams/OneDrive uninstall operations. Office 2007 through Microsoft 365/2024 are covered by the documented scrubber options. Corrupt, unsupported, orphaned, or unusually packaged installations may require manual repair; unknown uninstall commands and remaining detected Office products stop the deployment. This is not a guarantee that every historical Office artifact is erased. No automatic reboot or resume task is created. +Transient failures get bounded recovery before deployment stops: + +- HTTP downloads, including the ODT discovery page, get three attempts. ODT `/download` also gets three attempts using the same staging folder, before any app removal. An unrecognized discovery page, invalid signature, or invalid staged payload still fails validation. +- Machine and per-user MSI removal retry Windows Installer's [busy result, `1618`](https://learn.microsoft.com/en-us/windows/win32/msi/error-codes), up to five attempts with 15 seconds between attempts. Other installer failure codes retain their existing handling. The script does not kill an unrelated installer or blindly repeat an Office installation or scrub. +- After successful operations, machine removal and installation verification allow up to 60 seconds of polling for registry/package state to settle. The user's Teams add-in removal has the same allowance. Reads that fail still raise an error; inaccessible state is not treated as proof that an app is gone. +- Appx removal checks whether the exact package disappeared even when the removal command reports an error. If it remains, removal retries up to three times, each followed by the verification wait. Installed and provisioned packages must both be absent before continuing. +- A process that exits just before forced shutdown is tolerated. Failure to unregister an already-completed cleanup task is logged and does not stop installation; its completion marker makes subsequent task runs a no-op. + +Retries and waits are recorded in the diagnostic log. Persistent failures still stop the run with an error; these recovery paths do not turn incomplete deployment into success. Retry counts and delays are grouped in `Get-OfficeDeploymentDefinitions`; the standalone user helper has its MSI retry settings in `Get-OfficeUserCleanupDefinitions`. + ## Identity cleanup and absent users The core script clears Office 15/16 identity/licensing registry keys and Office licensing token folders in each locally available non-special Windows profile, loading unloaded user hives when needed. Unavailable profiles/containers stop deployment before removal. FSLogix/roaming profiles that are not registered locally are outside this script's coverage. Credential Manager belongs to each user. A limited-privilege scheduled task clears Office-prefixed credentials and removes per-user classic Teams. Before reinstallation begins, it also removes the user's old Teams meeting add-in and OneDrive. It runs immediately where a user session is available; otherwise it runs at that user's next sign-in. No passwords are stored. These tasks are named `Emberkom-OfficeCleanup--`. +An HKLM uninstall entry does not always mean the Teams meeting add-in is installed per-machine. The main script checks its actual machine registration through the read-only Windows Installer API before attempting a SYSTEM uninstall. The user helper checks both HKCU and HKLM uninstall entries, then selects only add-in products registered for that user. Removal is verified against that user's MSI registration, so another user's or a leftover display entry cannot cause a false failure. MSI query errors stop cleanup; the script does not delete uninstall registry keys to bypass verification. See [Microsoft's installation context enumeration API](https://learn.microsoft.com/en-us/windows/win32/api/msi/nf-msi-msienumproductsexw). + A file lock serializes user uninstallers with the transition to reinstallation. Once the protected `reinstall-started` marker is written, later user tasks preserve the Teams meeting add-in and OneDrive so they cannot uninstall the newly deployed apps. For absent users, OneDrive's per-machine installer handles migration; an existing per-user Teams meeting add-in can remain even when the Teams client is not reinstalled. Cleanup completion does not mean that every old per-user companion artifact was purged. Office credentials and classic Teams are still cleaned on the next sign-in. Windows work/school registration, WAM/AAD BrokerPlugin, generic Windows credentials, and device enrollment are preserved. This intentionally does not remove every Microsoft sign-in token. Microsoft's [activation reset guide](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365-apps/activation/reset-activation-state) distinguishes Office caches from shared WAM and workplace registration state. @@ -105,6 +117,8 @@ A deployment is reported as **InstalledWithUserCleanupPending** if any user task Syncro may flag nonzero results as errors; read the printed status and pending SIDs. Get Help recommends a restart after a successful scrub even when the installer does not return 3010. Schedule that restart separately. +If machine companion removal still fails verification, the error identifies the remaining component, version, and registry location, along with the uninstall log folder. The main log also records which add-in registrations were left to user cleanup. An uninstall exit code of `1605` alone does not establish that all users' installations are gone; Windows Installer context determines which stage handles the add-in. This failure occurs before Office scrub, identity reset, and reinstallation, but companion apps may already have been removed. + The main script uses the overridden `Write-Output` and `Write-Error` from `Tools.ps1` for actions, retries, failures, and the final receipt, writing to its existing `$Global:LogFile`. Internal action messages suppress the logger's echoed success output to keep function results separate from diagnostics. The mode notice, log location, and final receipt use `Microsoft.PowerShell.Utility\Write-Output` for Syncro. Errors are logged and also printed to Syncro. Native PowerShell relaunch reloads Tools and restores the caller's log path. Run the core through the shim/Tools execution context, not as an independent file without Tools. Process stdout/stderr logs, options, generated XML, and downloaded media remain in `%ProgramData%\EmberkomOfficeDeployment\`. The main script records this folder in the Tools log and receipt. The separate limited-user cleanup task does not share the elevated Tools execution context; its transcript remains in `%LOCALAPPDATA%\Emberkom\OfficeDeployment\.log` for each user. Retained media can consume several GB per attempt. A validation-only folder can be removed after reviewing its results; for deployment folders, first remove all associated scheduled tasks. ODT/Get Help may also write diagnostic logs to the executing account's temp directory. @@ -113,7 +127,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. They require Windows PowerShell 5.1 and exercise the default validation gate (including `Force`), explicit deployment opt-out, log/console routing with the real Tools helpers, XML, removal-result handling, bounded cache deletion, companion installer failures/verification, deferred cleanup protection, and the unchanged `Run-Script` receiving injected strings through the shim with a mocked workload. An inert executable checks actual native argument passing; a 32-bit Windows PowerShell child checks relaunch into 64-bit Windows PowerShell 5.1 and exit-code propagation. They do not run Microsoft installers or clear actual credentials. +Run `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\Install-MicrosoftOffice365.Tests.ps1` for offline checks. They require Windows PowerShell 5.1 and exercise the default validation gate (including `Force`), explicit deployment opt-out, log/console routing with the real Tools helpers, XML, removal-result handling, bounded cache deletion, companion installer failures/verification, deferred cleanup protection, and the unchanged `Run-Script` receiving injected strings through the shim with a mocked workload. Recovery checks simulate busy MSI, delayed registration, transient downloads, Appx removal races, persistent failures, and completed-task housekeeping errors. An inert executable checks actual native argument passing; a 32-bit Windows PowerShell child checks relaunch into 64-bit Windows PowerShell 5.1 and exit-code propagation. They do not run Microsoft installers or clear actual 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/resources/office/Office-UserCleanup.ps1 b/resources/office/Office-UserCleanup.ps1 index b3a1808..d9bfcae 100644 --- a/resources/office/Office-UserCleanup.ps1 +++ b/resources/office/Office-UserCleanup.ps1 @@ -1,8 +1,13 @@ #Requires -Version 5.1 -# EmberkomOfficeUserCleanup-v2 +# EmberkomOfficeUserCleanup-v4 # Run only as the affected user, at limited privilege; staged by the Office installer. param([Parameter(Mandatory = $true)][ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId) +function Get-OfficeUserCleanupDefinitions { + # This helper runs independently of Tools.ps1 and the main installer's functions. + @{ MsiBusyAttempts=5; MsiBusyRetrySeconds=15; RegistrationCheckAttempts=13; RegistrationCheckSeconds=5 } +} + function Test-OfficeCredentialTarget { param([string]$Target) # Preserve generic Azure AD, WindowsLive, OneDrive and MicrosoftAccount credentials. @@ -72,21 +77,69 @@ function Remove-OfficeUserLegacyTeams { if ((Test-Path -LiteralPath (Join-Path $teamsRoot 'current\Teams.exe')) -or (Test-Path -LiteralPath $teamsKey)) { throw 'Classic Teams remains registered or installed for this user.' } } +function Test-OfficeUserMsiProduct { + param([Parameter(Mandatory=$true)][ValidatePattern('^\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\}$')][string]$ProductCode) + if (!('Emberkom.OfficeUserMsi' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +namespace Emberkom { + public static class OfficeUserMsi { + [DllImport("msi.dll", CharSet=CharSet.Unicode, ExactSpelling=true)] + private static extern uint MsiEnumProductsExW(string product, string userSid, uint context, uint index, IntPtr code, IntPtr installedContext, IntPtr sid, IntPtr sidLength); + public static uint Find(string product) { + // Native NULL selects this user; 3 includes managed/unmanaged per-user products only. + return MsiEnumProductsExW(product, null, 3, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); + } + } +} +'@ + } + $code = [Emberkom.OfficeUserMsi]::Find($ProductCode) + if ($code -eq 0) { return $true } + if ($code -in @(259, 1605)) { return $false } + throw "Cannot determine this user's MSI registration for $ProductCode (Win32 $code)." +} + +function Get-OfficeUserTeamsAddinEntries { + # A per-user MSI can have an HKLM uninstall entry. Ask Windows Installer which + # products belong to this user instead of treating the hive as installation scope. + $roots = @('HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall', 'HKCU:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall', 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall') + $seen = @{} + foreach ($root in $roots) { + if (!(Test-Path -LiteralPath $root)) { continue } + foreach ($entry in @(Get-ItemProperty -Path "$root\*" -ErrorAction Stop | Where-Object { $_.DisplayName -eq 'Microsoft Teams Meeting Add-in for Microsoft Office' -and $_.Publisher -like 'Microsoft*' })) { + if ($seen.ContainsKey($entry.PSChildName)) { continue } + $seen[$entry.PSChildName] = $true + if (Test-OfficeUserMsiProduct $entry.PSChildName) { $entry } + } + } +} + function Remove-OfficeUserCompanions { param([switch]$PreserveReinstalledApps) + $definitions = Get-OfficeUserCleanupDefinitions Remove-OfficeUserLegacyTeams if ($PreserveReinstalledApps) { Write-Host 'Reinstallation has started. Preserving the Teams meeting add-in and leaving per-user OneDrive migration to the per-machine OneDrive installer.' return } - $uninstallRoot = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall' - if (Test-Path -LiteralPath $uninstallRoot) { - foreach ($entry in @(Get-ItemProperty -Path "$uninstallRoot\*" -ErrorAction Stop | Where-Object { $_.DisplayName -eq 'Microsoft Teams Meeting Add-in for Microsoft Office' -and $_.Publisher -like 'Microsoft*' })) { - if ($entry.PSChildName -notmatch '^\{[0-9A-Fa-f-]{36}\}$') { throw 'Unexpected per-user Teams add-in product code.' } + foreach ($entry in @(Get-OfficeUserTeamsAddinEntries)) { + Write-Host "Removing this user's Teams meeting add-in $($entry.DisplayVersion), $($entry.PSChildName)." + for ($attempt = 1; ; $attempt++) { $process = Start-Process -FilePath "$env:WINDIR\System32\msiexec.exe" -ArgumentList "/x $($entry.PSChildName) /qn /norestart" -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop - if ($process.ExitCode -notin @(0, 1605, 1614)) { throw "Per-user Teams add-in removal needs attention (exit $($process.ExitCode))." } - if (Test-Path -LiteralPath $entry.PSPath) { throw 'Per-user Teams meeting add-in remains registered.' } + if ($process.ExitCode -ne 1618 -or $attempt -ge $definitions.MsiBusyAttempts) { break } + Write-Host "Windows Installer is busy; retrying the user add-in removal in $($definitions.MsiBusyRetrySeconds) seconds (attempt $attempt of $($definitions.MsiBusyAttempts))." + Start-Sleep -Seconds $definitions.MsiBusyRetrySeconds } + if ($process.ExitCode -notin @(0, 1605, 1614)) { throw "Per-user Teams add-in removal needs attention (exit $($process.ExitCode)), product $($entry.PSChildName)." } + for ($attempt = 1; $attempt -le $definitions.RegistrationCheckAttempts; $attempt++) { + $remains = Test-OfficeUserMsiProduct $entry.PSChildName + if (!$remains -or $attempt -eq $definitions.RegistrationCheckAttempts) { break } + if ($attempt -eq 1) { Write-Host 'Waiting for the user add-in registration to disappear.' } + Start-Sleep -Seconds $definitions.RegistrationCheckSeconds + } + if ($remains) { throw "Teams meeting add-in $($entry.PSChildName) remains registered for this user." } } $oneDriveKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\OneDriveSetup.exe' if (Test-Path -LiteralPath $oneDriveKey) { diff --git a/tests/Install-MicrosoftOffice365.Tests.ps1 b/tests/Install-MicrosoftOffice365.Tests.ps1 index 39bb330..6f082d0 100644 --- a/tests/Install-MicrosoftOffice365.Tests.ps1 +++ b/tests/Install-MicrosoftOffice365.Tests.ps1 @@ -34,6 +34,95 @@ try { . ([scriptblock]::Create($definition.Extent.Text)) } } + # Exercise the real bounded retry loops without delaying offline tests. + function Start-Sleep { param([int]$Seconds) $script:testSleeps += $Seconds } + $script:testSleeps = @() + & { + $script:probeCalls=0; $script:testSleeps=@() + $result = Wait-OfficeResult { $script:probeCalls++; if ($script:probeCalls -eq 3) { [pscustomobject]@{Version='ready'} } } 'delayed fixture registration' + Assert-OfficeTest ($result.Version -eq 'ready' -and $script:probeCalls -eq 3 -and $script:testSleeps.Count -eq 2) 'Delayed registration must return the verified value without leaking log text.' + $script:probeCalls=0; $script:testSleeps=@() + $result = Wait-OfficeResult { $script:probeCalls++; $false } 'missing fixture registration' + Assert-OfficeTest ($null -eq $result -and $script:probeCalls -eq (Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts -and $script:testSleeps.Count -eq ($script:probeCalls - 1)) 'Registration waits must stop at the configured bound.' + $script:probeCalls=0 + Assert-OfficeThrows { Wait-OfficeResult { $script:probeCalls++; throw 'Registry access denied' } 'unreadable fixture' } 'Registry access denied' + Assert-OfficeTest ($script:probeCalls -eq 1) 'Failed inventory reads must not be treated as absent installations.' + } + & { + function Start-Process { + param($FilePath,$ArgumentList,$WorkingDirectory,[switch]$Wait,[switch]$PassThru,$WindowStyle,$RedirectStandardOutput,$RedirectStandardError) + $script:processCalls++; $script:processLogs += $RedirectStandardOutput + if ($script:processExit -eq 1618 -and $script:processRecovers -and $script:processCalls -eq 3) { return [pscustomobject]@{ExitCode=0} } + [pscustomobject]@{ExitCode=$script:processExit} + } + foreach ($mode in @('recovers','busy','fatal','reboot','not-msi','null-code')) { + $script:processCalls=0; $script:processLogs=@(); $script:testSleeps=@(); $script:processRecovers=$mode -eq 'recovers' + $script:processExit = switch ($mode) { 'fatal' {1603}; 'reboot' {3010}; 'null-code' {$null}; default {1618} } + $executable = if ($mode -eq 'not-msi') { 'bootstrapper.exe' } else { 'msiexec.exe' } + $file = Join-Path $testRoot $executable + if ($mode -eq 'null-code') { Assert-OfficeThrows { Invoke-OfficeProcess $file '/x fixture' (Join-Path $testRoot 'msi') } 'No exit code'; continue } + $code = Invoke-OfficeProcess $file '/x fixture' (Join-Path $testRoot 'msi') + $expectedCalls = if ($mode -eq 'recovers') {3} elseif ($mode -eq 'busy') {(Get-OfficeDeploymentDefinitions).MsiBusyAttempts} else {1} + $expectedCode = if ($mode -eq 'recovers') {0} else {$script:processExit} + Assert-OfficeTest ($code -eq $expectedCode -and $script:processCalls -eq $expectedCalls -and $script:testSleeps.Count -eq ($expectedCalls - 1)) "Incorrect retry behavior for $mode." + Assert-OfficeTest (@($script:processLogs | Select-Object -Unique).Count -eq $expectedCalls) 'MSI retry output logs must not overwrite earlier attempts.' + } + } + & { + function Invoke-WebRequest { + [CmdletBinding()] + param([switch]$UseBasicParsing,$Uri,$OutFile,$TimeoutSec) + $script:downloadCalls++ + if (!$script:downloadRecovers -or $script:downloadCalls -eq 1) { throw 'Temporary network failure' } + [IO.File]::WriteAllText($OutFile, 'downloaded fixture') + } + $script:downloadCalls=0; $script:downloadRecovers=$true + Save-OfficeDownload 'https://fixture.invalid/' (Join-Path $testRoot 'download') 2>$null + Assert-OfficeTest ($script:downloadCalls -eq 2 -and (Get-Content -LiteralPath (Join-Path $testRoot 'download') -Raw) -eq 'downloaded fixture') 'A transient download error should recover.' + $script:downloadCalls=0; $script:downloadRecovers=$false + Assert-OfficeThrows { Save-OfficeDownload 'https://fixture.invalid/' (Join-Path $testRoot 'download') 2>$null } 'Temporary network failure' + Assert-OfficeTest ($script:downloadCalls -eq (Get-OfficeDeploymentDefinitions).DownloadAttempts) 'Persistent download failure must remain bounded.' + } + & { + function Remove-AppxPackage { + param($Package,[switch]$AllUsers) + $script:appxCalls++ + if ($script:appxMode -eq 'already-gone') { $script:appxPresent=$false; throw 'Package already removed by another operation' } + if ($script:appxMode -eq 'failure' -or ($script:appxMode -eq 'recovers' -and $script:appxCalls -eq 1)) { throw 'Transient package in use' } + $script:appxPresent=$false + } + function Remove-AppxProvisionedPackage { param($PackageName,[switch]$Online,[switch]$AllUsers) Remove-AppxPackage -Package $PackageName -AllUsers } + function Get-AppxPackage { + param([switch]$AllUsers) + if ($script:appxMode -eq 'query-failure') { throw 'Appx inventory access denied' } + if ($script:appxPresent) { [pscustomobject]@{PackageFullName='fixture'; PackageName='fixture'} } + } + function Get-AppxProvisionedPackage { param([switch]$Online) Get-AppxPackage -AllUsers } + foreach ($provisioned in @($false,$true)) { + foreach ($script:appxMode in @('success','already-gone','recovers','failure','query-failure')) { + $script:appxPresent=$true; $script:appxCalls=0 + if ($script:appxMode -eq 'failure') { + Assert-OfficeThrows { Remove-OfficeAppxEntry 'fixture' -Provisioned:$provisioned } 'Appx package remains' + Assert-OfficeTest ($script:appxCalls -eq (Get-OfficeDeploymentDefinitions).AppxRemovalAttempts) 'Persistent Appx removal failure must be bounded.' + } elseif ($script:appxMode -eq 'query-failure') { + Assert-OfficeThrows { Remove-OfficeAppxEntry 'fixture' -Provisioned:$provisioned } 'Appx inventory access denied' + Assert-OfficeTest ($script:appxCalls -eq 1) 'Appx read errors must propagate instead of passing verification.' + } else { + $output = @(Remove-OfficeAppxEntry 'fixture' -Provisioned:$provisioned) + $expectedCalls = if ($script:appxMode -eq 'recovers') {2} else {1} + Assert-OfficeTest (!$script:appxPresent -and $script:appxCalls -eq $expectedCalls -and $output.Count -eq 0) "Appx removal did not recover cleanly: $script:appxMode, provisioned=$provisioned." + } + } + } + } + & { + function Get-OfficeRunningApps { [pscustomobject]@{Id=123; HasExited=$script:appHasExited} } + function Stop-Process { throw 'Process is gone or access was denied.' } + $script:appHasExited=$true + Stop-OfficeDeploymentApps ([pscustomobject]@{OfficeAppShutdown='Force'}) + $script:appHasExited=$false + Assert-OfficeThrows { Stop-OfficeDeploymentApps ([pscustomobject]@{OfficeAppShutdown='Force'}) } 'Process is gone or access was denied' + } foreach ($value in @($null, '', ' ', 'true', ' TRUE ', '$true', '1', 'yes')) { $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; ValidateBeforeChanges=$value} Assert-OfficeTest ($options.ValidateBeforeChanges -is [bool] -and $options.ValidateBeforeChanges) "Validation must be on for '$value'." @@ -119,15 +208,18 @@ try { $mediaFixtureZip = Join-Path $testRoot 'gethelp-fixture.zip' Add-Type -AssemblyName System.IO.Compression.FileSystem [IO.Compression.ZipFile]::CreateFromDirectory($zipSource, $mediaFixtureZip) - $script:mediaSignatures = @(); $script:mediaProcesses = @() + $script:mediaSignatures = @(); $script:mediaProcesses = @(); $script:mediaDownloadCalls = 0 function Invoke-WebRequest { [CmdletBinding()] param([switch]$UseBasicParsing, [string]$Uri, [int]$TimeoutSec) [pscustomobject]@{Content='https://download.microsoft.com/test/officedeploymenttool_test.exe'} } function Save-OfficeDownload { - param([string]$Uri, [string]$Path) - if ([IO.Path]::GetFileName($Path) -eq 'GetHelp.zip') { + param([string]$Uri, [string]$Path, [int]$TimeoutSeconds) + if ([IO.Path]::GetFileName($Path) -eq 'odt-download-page.html') { + Assert-OfficeTest ($TimeoutSeconds -eq (Get-OfficeDeploymentDefinitions).OdtPageTimeoutSeconds) 'ODT page must use the retried downloader with its configured timeout.' + [IO.File]::WriteAllText($Path, 'https://download.microsoft.com/test/officedeploymenttool_test.exe') + } elseif ([IO.Path]::GetFileName($Path) -eq 'GetHelp.zip') { [IO.File]::Copy($mediaFixtureZip, $Path) } elseif ([IO.Path]::GetFileName($Path) -eq 'Office-UserCleanup.ps1') { [IO.File]::WriteAllText($Path, '# ' + (Get-OfficeDeploymentDefinitions).HelperVersion) @@ -146,6 +238,8 @@ try { if ([IO.Path]::GetFileName($FilePath) -eq 'odt.exe' -and $Arguments -like '/quiet /extract:*') { [IO.File]::WriteAllText((Join-Path $mediaWorkspace 'ODT\setup.exe'), 'Inert ODT fixture; never executed.') } elseif ([IO.Path]::GetFileName($FilePath) -eq 'setup.exe' -and $Arguments -like '/download *') { + $script:mediaDownloadCalls++ + if ($script:mediaDownloadCalls -eq 1) { return 12029 } $payload = Join-Path $mediaWorkspace 'ODT\Office\Data\16.0.12345.67890' $null = [IO.Directory]::CreateDirectory($payload) foreach ($name in @('stream.x64.x-none.dat', 'stream.x64.en-us.dat')) { [IO.File]::WriteAllText((Join-Path $payload $name), 'Inert Office payload.') } @@ -158,7 +252,7 @@ try { Assert-OfficeTest ($media.Scrubber -in $script:mediaSignatures -and $media.Setup -in $script:mediaSignatures) 'Extracted Get Help and ODT must still pass signature checks.' Assert-OfficeTest ($media.Version -eq '16.0.12345.67890' -and $media.Companions.Count -eq 3 -and !$media.Companions.ContainsKey('Teams')) 'Media staging lost its build or no-Teams selection.' Assert-OfficeTest (([xml](Get-Content -LiteralPath $media.Config -Raw)).Configuration.Add.Version -eq $media.Version) 'Staged configuration must pin the downloaded build.' - Assert-OfficeTest (($script:mediaProcesses -join ',') -eq 'odt.exe,setup.exe') 'Staging attempted to run a scrubber or companion installer.' + Assert-OfficeTest (($script:mediaProcesses -join ',') -eq 'odt.exe,setup.exe,setup.exe') 'Staging must retry the failed download without launching a scrubber or companion installer.' } & { $script:staged = @(); $script:verified = @() @@ -178,10 +272,16 @@ try { Assert-OfficeThrows { Initialize-OfficeCompanionMedia $testRoot } 'Untrusted companion' } & { - function Get-OfficeMachineWebViewVersion { if ($script:webViewPresent) { '140.0.0.1' } } + function Get-OfficeMachineWebViewVersion { + if ($script:webViewPresent) { + if ($script:appMode -eq 'delayed-success') { $script:webViewChecks++; if ($script:webViewChecks -lt 3) { return } } + '140.0.0.1' + } + } function Invoke-OfficeProcess { param($FilePath,$Arguments,$LogPrefix) $script:appCalls += "$FilePath $Arguments" + $script:lastInstalledApp=$FilePath if ($script:appMode -eq "fail-$FilePath") { return 42 } if ($FilePath -eq 'WebView2') { $script:webViewPresent = $true } if ($script:appMode -eq 'reboot' -and $FilePath -eq 'OneDrive') { return 3010 } @@ -189,16 +289,21 @@ try { } function Get-AppxProvisionedPackage { param([switch]$Online,$ErrorAction) + if ($script:appMode -eq 'delayed-success') { $script:packageChecks[$script:lastInstalledApp]++; if ($script:packageChecks[$script:lastInstalledApp] -lt 3) { return } } if ($script:appMode -ne 'missing-Teams') { [pscustomobject]@{DisplayName='MSTeams'; PackageName='MSTeams_1.0.0.0_neutral_~_8wekyb3d8bbwe'; Version='1.0.0.0'} } if ($script:appMode -ne 'missing-NewOutlook') { [pscustomobject]@{DisplayName='Microsoft.OutlookForWindows'; PackageName='Microsoft.OutlookForWindows_1.0.0.0_neutral_~_8wekyb3d8bbwe'; Version='1.0.0.0'} } } - function Get-OfficeMachineOneDrive { if ($script:appMode -ne 'missing-OneDrive') { [pscustomobject]@{Path='inert.exe'; Version='26.1.2.3'} } } + function Get-OfficeMachineOneDrive { + if ($script:appMode -eq 'delayed-success') { $script:oneDriveChecks++; if ($script:oneDriveChecks -lt 3) { return } } + if ($script:appMode -ne 'missing-OneDrive') { [pscustomobject]@{Path='inert.exe'; Version='26.1.2.3'} } + } function Assert-OfficeMicrosoftSignature { } $media = @{WebView2='WebView2'; OneDrive='OneDrive'; Teams='Teams'; NewOutlook='NewOutlook'} - foreach ($script:appMode in @('success','reboot','fail-WebView2','fail-OneDrive','fail-Teams','fail-NewOutlook','missing-OneDrive','missing-Teams','missing-NewOutlook')) { + foreach ($script:appMode in @('success','delayed-success','reboot','fail-WebView2','fail-OneDrive','fail-Teams','fail-NewOutlook','missing-OneDrive','missing-Teams','missing-NewOutlook')) { $script:webViewPresent = $false; $script:appCalls = @(); $failure = $null; $result = $null + $script:webViewChecks=0; $script:oneDriveChecks=0; $script:packageChecks=@{} try { $result = Install-OfficeCompanionApps $media $testRoot -InstallTeams $true } catch { $failure = $_ } - if ($script:appMode -in @('success','reboot')) { + if ($script:appMode -in @('success','delayed-success','reboot')) { $expectedCode = if ($script:appMode -eq 'reboot') { 3010 } else { 0 } Assert-OfficeTest ($null -eq $failure -and $result.ExitCode -eq $expectedCode) "Unexpected companion result for $script:appMode : $failure" Assert-OfficeTest ($result.Versions.OneDrive -eq '26.1.2.3' -and $result.Versions.Teams -eq '1.0.0.0' -and $result.Versions.NewOutlook -eq '1.0.0.0') 'Companion verification receipt is incomplete.' @@ -275,6 +380,96 @@ try { Assert-OfficeThrows { Get-OfficeOneDriveCommand '"C:\Users\someone\OneDriveSetup.exe" /uninstall' @('C:\Program Files\Microsoft OneDrive') } 'allowlist' Assert-OfficeThrows { Get-OfficeOneDriveCommand '"C:\Program Files\Microsoft OneDrive\OneDriveSetup.exe" /uninstall & calc.exe' @('C:\Program Files\Microsoft OneDrive') } 'allowlist' + # Compile and exercise the real read-only MSI queries for a nonexistent product. + $absentProduct = '{' + [guid]::NewGuid().ToString() + '}' + Assert-OfficeTest (!(Test-OfficeMachineMsiProduct $absentProduct)) 'An unknown product must not be classified as a machine MSI.' + Assert-OfficeTest (!(Test-OfficeUserMsiProduct $absentProduct)) 'An unknown product must not be classified as a current-user MSI.' + Assert-OfficeThrows { Test-OfficeMachineMsiProduct 'not-a-guid' } 'ProductCode' + Assert-OfficeThrows { Test-OfficeUserMsiProduct 'not-a-guid' } 'ProductCode' + Assert-OfficeTest ($helperAst.Extent.Text.Contains((Get-OfficeDeploymentDefinitions).HelperVersion)) 'The staged helper version contract must match the checked-in helper.' + + # HKLM can contain a per-user Teams add-in registration. Never run its MSI as SYSTEM. + & { + $addin = [pscustomobject]@{DisplayName='Microsoft Teams Meeting Add-in for Microsoft Office'; DisplayVersion='1.26.25904'; PSChildName='{11111111-2222-3333-4444-555555555555}'; PSPath='Registry::HKEY_LOCAL_MACHINE\Software\Fixture\Addin'} + $script:companionEntries=@($addin); $script:machineRegistered=$false; $script:removalCalls=@() + function Get-OfficeUninstallEntries { $script:companionEntries } + function Test-OfficeMachineMsiProduct { $script:machineRegistered } + function Get-AppxProvisionedPackage { param([switch]$Online) } + function Get-AppxPackage { param([switch]$AllUsers) } + function Assert-OfficeMicrosoftSignature { } + function Invoke-OfficeProcess { + param($FilePath,$Arguments,$LogPrefix) + $script:removalCalls += $Arguments + if ($script:removalMode -eq 'success') { $script:machineRegistered=$false } + if ($script:removalMode -eq 'unknown') { return 1605 } + if ($script:removalMode -eq 'reboot') { return 3010 } + if ($script:removalMode -eq 'failure') { return 1603 } + return 0 + } + $reboot = Remove-OfficeCompanionApps $testRoot + Assert-OfficeTest (!$reboot -and $script:removalCalls.Count -eq 0) 'An HKLM entry without machine MSI registration must be left to user cleanup.' + foreach ($mode in @('success','remaining','unknown','failure','reboot')) { + $script:machineRegistered=$true; $script:removalMode=$mode; $script:removalCalls=@() + if ($mode -in @('remaining','unknown')) { + Assert-OfficeThrows { Remove-OfficeCompanionApps $testRoot } 'registrations remain.*Microsoft Teams Meeting Add-in.*1\.26\.25904.*Fixture' + } elseif ($mode -eq 'failure') { + Assert-OfficeThrows { Remove-OfficeCompanionApps $testRoot } 'Could not remove.*1603' + } else { + $reboot=Remove-OfficeCompanionApps $testRoot + Assert-OfficeTest ($reboot -eq ($mode -eq 'reboot')) "Incorrect reboot result for machine MSI mode $mode." + } + Assert-OfficeTest ($script:removalCalls.Count -eq 1 -and $script:removalCalls[0] -like ('/x ' + $addin.PSChildName + ' /qn /norestart*')) 'A real machine add-in must still be uninstalled silently.' + } + $script:companionEntries=@([pscustomobject]@{DisplayName='Microsoft OneDrive'; DisplayVersion='26.1'; PSPath='Registry::HKEY_LOCAL_MACHINE\Software\Fixture\OneDrive'; UninstallString=('"' + $env:ProgramFiles + '\Microsoft OneDrive\OneDriveSetup.exe" /uninstall /allusers')}) + $script:removalMode='remaining' + Assert-OfficeThrows { Remove-OfficeCompanionApps $testRoot } 'registrations remain.*Microsoft OneDrive.*26\.1' + $script:companionEntries=@($addin) + function Test-OfficeMachineMsiProduct { throw 'MSI registration query failed' } + Assert-OfficeThrows { Remove-OfficeCompanionApps $testRoot } 'MSI registration query failed' + } + & { + $mine = [pscustomobject]@{DisplayName='Microsoft Teams Meeting Add-in for Microsoft Office'; Publisher='Microsoft'; DisplayVersion='1.26.25904'; PSChildName='{11111111-2222-3333-4444-555555555555}'} + $other = [pscustomobject]@{DisplayName=$mine.DisplayName; Publisher='Microsoft'; PSChildName='{22222222-2222-3333-4444-555555555555}'} + function Test-Path { param($LiteralPath) $true } + function Get-ItemProperty { param($Path) if ($Path -like 'HKLM:*') { $mine; $other } } + function Test-OfficeUserMsiProduct { param($ProductCode) $ProductCode -eq $mine.PSChildName } + $found=@(Get-OfficeUserTeamsAddinEntries) + Assert-OfficeTest ($found.Count -eq 1 -and $found[0].PSChildName -eq $mine.PSChildName) 'User cleanup must discover its HKLM-advertised add-in, deduplicate registry views, and exclude other contexts.' + function Test-OfficeUserMsiProduct { $false } + Assert-OfficeTest (@(Get-OfficeUserTeamsAddinEntries).Count -eq 0) 'User cleanup must not claim products registered only for another user or machine.' + } + & { + function Remove-OfficeUserLegacyTeams { } + function Get-OfficeUserTeamsAddinEntries { [pscustomobject]@{DisplayVersion='1.26.25904'; PSChildName='{11111111-2222-3333-4444-555555555555}'} } + function Test-Path { $false } + function Test-OfficeUserMsiProduct { $script:userMsiRemains } + function Start-Process { + param($FilePath,$ArgumentList,$WindowStyle,[switch]$Wait,[switch]$PassThru) + Assert-OfficeTest ($FilePath -like '*\msiexec.exe' -and $ArgumentList -like '/x * /qn /norestart' -and $Wait -and $WindowStyle -eq 'Hidden') 'User MSI uninstall must remain silent and synchronous.' + [pscustomobject]@{ExitCode=$script:userMsiExit} + } + $script:userMsiRemains=$false; $script:userMsiExit=0 + Remove-OfficeUserCompanions + $script:userMsiRemains=$true + Assert-OfficeThrows { Remove-OfficeUserCompanions } 'remains registered for this user' + $script:userMsiExit=1605 + Assert-OfficeThrows { Remove-OfficeUserCompanions } 'remains registered for this user' + $script:userMsiExit=1603 + Assert-OfficeThrows { Remove-OfficeUserCompanions } 'removal needs attention.*1603' + function Start-Process { + $script:userMsiStarts++ + $code = if ($script:userMsiRecovers -and $script:userMsiStarts -eq 3) {0} else {1618} + [pscustomobject]@{ExitCode=$code} + } + function Test-OfficeUserMsiProduct { $script:userMsiChecks++; $script:userMsiChecks -lt 3 } + $script:userMsiStarts=0; $script:userMsiChecks=0; $script:userMsiRecovers=$true + Remove-OfficeUserCompanions + Assert-OfficeTest ($script:userMsiStarts -eq 3 -and $script:userMsiChecks -eq 3) 'User MSI cleanup must recover from busy MSI and delayed registration removal.' + $script:userMsiStarts=0; $script:userMsiRecovers=$false + Assert-OfficeThrows { Remove-OfficeUserCompanions } 'removal needs attention.*1618' + Assert-OfficeTest ($script:userMsiStarts -eq (Get-OfficeUserCleanupDefinitions).MsiBusyAttempts) 'User MSI busy retries must be bounded.' + } + # Exercise real cache deletion against synthetic profiles only. Documents/SSO stay intact. $profile = Join-Path $testRoot 'profile' $cache = Join-Path $profile 'AppData\Local\Microsoft\Office\Licenses' @@ -298,6 +493,7 @@ try { & { function Invoke-OfficeProcess { return $script:installCode } function Get-ItemProperty { return $script:installed } + function Test-Path { $true } $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Standard'; OfficeArchitecture='64'} $media = [pscustomobject]@{Setup='inert.exe'; Config='inert.xml'; Version='16.0.1.2'} $script:installed = [pscustomobject]@{ProductReleaseIds='O365BusinessRetail'; Platform='x64'; VersionToReport='16.0.1.2'} @@ -311,6 +507,9 @@ try { Assert-OfficeThrows { Install-OfficeMedia $options $media $testRoot } 'did not match' $script:installCode=42 Assert-OfficeThrows { Install-OfficeMedia $options $media $testRoot } 'installation failed' + $script:installCode=0; $script:installed.VersionToReport='16.0.1.2'; $script:officeChecks=0 + function Get-ItemProperty { $script:officeChecks++; if ($script:officeChecks -ge 3) { $script:installed } } + Assert-OfficeTest ((Install-OfficeMedia $options $media $testRoot) -eq 0 -and $script:officeChecks -eq 3) 'Office verification must tolerate delayed Click-to-Run registration.' } & { $script:registered = @(); $script:started = @(); $script:removed = @() @@ -327,6 +526,9 @@ try { $pending = Start-OfficeUserCleanup $profiles ([pscustomobject]@{Helper='C:\secure\helper.ps1'}) (Join-Path $testRoot ('a'*32)) Assert-OfficeTest ($script:registered.Count -eq 2 -and $script:started.Count -eq 1 -and $script:removed.Count -eq 1) 'User scheduling or completed task cleanup is incorrect.' Assert-OfficeTest ($pending.Count -eq 1 -and $pending[0] -eq 'logged-off') 'Logged-off user cleanup was reported complete.' + function Unregister-ScheduledTask { throw 'Task Scheduler is temporarily unavailable.' } + $pending = Start-OfficeUserCleanup $profiles ([pscustomobject]@{Helper='C:\secure\helper.ps1'}) (Join-Path $testRoot ('a'*32)) + Assert-OfficeTest ($pending.Count -eq 1 -and $pending[0] -eq 'logged-off') 'Completed task housekeeping must not fail deployment or mark completed cleanup pending.' } # Test orchestration with every machine mutation mocked.