From 136c88fedf10f2d17cdd098a56f15084f0ee1045 Mon Sep 17 00:00:00 2001 From: ek-dyoder Date: Wed, 21 Oct 2026 09:30:15 -0400 Subject: [PATCH] added a few fixes --- Install-MicrosoftOffice365.ps1 | 569 +++++++++++++++++---- Uninstall-MicrosoftOffice.ps1 | 28 +- docs/Office365-Deployment.md | 64 ++- resources/office/Office-UserCleanup.ps1 | 67 ++- rmm/Install-MicrosoftOffice365.ps1 | 3 + tests/Install-MicrosoftOffice365.Tests.ps1 | 530 +++++++++++++++++-- 6 files changed, 1103 insertions(+), 158 deletions(-) diff --git a/Install-MicrosoftOffice365.ps1 b/Install-MicrosoftOffice365.ps1 index 0ce5bf0..55acc72 100644 --- a/Install-MicrosoftOffice365.ps1 +++ b/Install-MicrosoftOffice365.ps1 @@ -31,13 +31,8 @@ function Get-OfficeDeploymentDefinitions { RepositoryRoot = 'https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master' OdtPage = 'https://www.microsoft.com/en-us/download/details.aspx?id=49117' OdtDownloadPattern = 'https://download\.microsoft\.com/[^"\s<>]+/officedeploymenttool_[a-zA-Z0-9_-]+\.exe' - GetHelpUrl = 'https://aka.ms/SaRA_EnterpriseVersionFiles' - GetHelpExecutable = 'GetHelpCmd.exe' - ScrubArguments = '-S OfficeScrubScenario -AcceptEula -OfficeVersion All' - ScrubScenarioPattern = '(?m)^\s*(\d{2}):' - ScrubScenarioSuccess = @('00', '66', '68') - ScrubExitSuccess = @(0, 66, 68) - HelperVersion = 'EmberkomOfficeUserCleanup-v2' + ManualScrubUrl = 'https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall' + HelperVersion = 'EmberkomOfficeUserCleanup-v4' Language = 'en-us' OfficeBuildPattern = '^16\.0\.\d+\.\d+$' OdtExcludedApps = @('Groove', 'OneDrive', 'Lync', 'Teams', 'OutlookForWindows') @@ -68,8 +63,16 @@ function Get-OfficeDeploymentDefinitions { DownloadTimeoutSeconds = 300 DownloadRetrySeconds = 3 OdtPageTimeoutSeconds = 120 - UserCleanupWaitMinutes = 5 - UserCleanupTaskMinutes = 15 + MsiBusyAttempts = 5 + MsiBusyRetrySeconds = 15 + # Installer processes have no separate elapsed-time cutoff; Syncro owns the + # overall run limit (configure 120 minutes). These are post-process checks. + RegistrationCheckAttempts = 61 + RegistrationCheckSeconds = 5 + AppxRemovalAttempts = 3 + UserCleanupWaitMinutes = 20 + UserCleanupTaskMinutes = 30 + MediaCacheDays = 7 } } @@ -81,6 +84,9 @@ function Get-OfficeDeploymentOptions { [string]$validate = $InputValues.ValidateBeforeChanges if ([string]::IsNullOrWhiteSpace($validate)) { $validate = 'true' } $validateOnly = ConvertTo-RmmBoolean -Value $validate -VariableName 'ValidateBeforeChanges' + [string]$defer = $InputValues.DeferReboot + if ([string]::IsNullOrWhiteSpace($defer)) { $defer = 'true' } + $deferReboot = ConvertTo-RmmBoolean -Value $defer -VariableName 'DeferReboot' [string]$subscription = $InputValues.OfficeSubscription $subscription = $subscription.Trim() # Accept previously documented individual names for existing saved RMM selections. @@ -94,7 +100,7 @@ function Get-OfficeDeploymentOptions { [string]$company = $InputValues.COMPANY $company = $company.Trim() if ($company -eq 'None') { $company = '' } - $options = @{ OfficeSubscription = $subscription; ProductId = $plans[$subscription]; Company = $company; ValidateBeforeChanges = $validateOnly } + $options = @{ OfficeSubscription = $subscription; ProductId = $plans[$subscription]; Company = $company; ValidateBeforeChanges = $validateOnly; DeferReboot = $deferReboot } # Derive this from the validated product mapping, including standalone Apps plans and legacy aliases. $options.InstallTeams = $options.ProductId -in $definitions.TeamsProducts foreach ($name in $choices.Keys) { @@ -134,8 +140,12 @@ function Assert-OfficeCompanionPlatform { } function New-OfficeWorkspace { + param( + [string]$Root = (Join-Path ([IO.Path]::GetTempPath()) 'EmberkomOfficeDeployment'), + [ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId = ([guid]::NewGuid().ToString('N')) + ) # Executable content must never be writable by a standard user. - $root = Join-Path $env:ProgramData 'EmberkomOfficeDeployment' + # Default to the execution account's temp location (SYSTEM under Syncro). $null = New-Item -ItemType Directory -Path $root -Force -ErrorAction Stop for ($item = Get-Item -LiteralPath $root -Force; $null -ne $item; $item = $item.Parent) { if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Deployment path traverses a reparse point: $($item.FullName)" } @@ -149,12 +159,198 @@ function New-OfficeWorkspace { } $acl.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544'))) Set-Acl -LiteralPath $root -AclObject $acl -ErrorAction Stop - $path = Join-Path $root ([guid]::NewGuid().ToString('N')) + $path = Join-Path $root $DeploymentId $null = New-Item -ItemType Directory -Path $path -ErrorAction Stop $null = New-Item -ItemType File -Path (Join-Path $path 'user-cleanup.lock') -ErrorAction Stop $path } +function New-OfficeUserWorkspace { + param($Media, [string]$Workspace) + # Only deferred user cleanup must survive routine temp purges. SYSTEM's temp + # directory may also be inaccessible to the limited users who run this helper. + $path = New-OfficeWorkspace -Root (Join-Path $env:ProgramData 'EmberkomOfficeDeployment') -DeploymentId (Split-Path -Leaf $Workspace) + $helper = Join-Path $path 'Office-UserCleanup.ps1' + Copy-Item -LiteralPath $Media.Helper -Destination $helper -ErrorAction Stop + $Media.Helper = $helper + $path +} + +function Assert-OfficeManagedPath { + param([string]$Root, [string]$Path) + $base = [IO.Path]::GetFullPath($Root).TrimEnd('\') + $target = [IO.Path]::GetFullPath($Path) + if (!$target.StartsWith($base + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "Path is outside the Office deployment root: $target" } + # Check ancestors before enumeration; never follow a junction during deletion or reuse. + for ($cursor = $target; $cursor; $cursor = Split-Path -Parent $cursor) { + if (Test-Path -LiteralPath $cursor) { + if ((Get-Item -LiteralPath $cursor -Force -ErrorAction Stop).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Deployment path traverses a reparse point: $cursor" } + } + } +} + +function Get-OfficeManagedFiles { + param([string]$Root, [string]$Path) + Assert-OfficeManagedPath $Root $Path + if (!(Test-Path -LiteralPath $Path)) { return } + $item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop + if (!$item.PSIsContainer) { return $item } + foreach ($child in @(Get-ChildItem -LiteralPath $Path -Force -ErrorAction Stop)) { + # Recurse ourselves so a nested junction is rejected BEFORE visiting its target. + Get-OfficeManagedFiles $Root $child.FullName + } +} + +function Remove-OfficeManagedItem { + param([string]$Root, [string]$Path) + Assert-OfficeManagedPath $Root $Path + if (!(Test-Path -LiteralPath $Path)) { return } + $null = @(Get-OfficeManagedFiles $Root $Path) + $null = Write-Output "Removing deployment artifact: $Path" + Remove-Item -LiteralPath ([IO.Path]::GetFullPath($Path)) -Recurse -Force -ErrorAction Stop +} + +function Get-OfficeStagingNames { + # Only our downloaded artifacts; never Office's installed files or servicing caches. + @('ODT', 'odt.exe', 'odt-download-page.html', 'GetHelp', 'GetHelp.zip', 'media-cache.json') + foreach ($installer in (Get-OfficeDeploymentDefinitions).CompanionInstallers.Values) { $installer.File } +} + +function Remove-OfficeStagingFiles { + param([string]$Root, [string]$Workspace) + Assert-OfficeManagedPath $Root $Workspace + foreach ($name in (Get-OfficeStagingNames)) { Remove-OfficeManagedItem $Root (Join-Path $Workspace $name) } +} + +function Complete-OfficeDeploymentFiles { + param([string]$Workspace, [string]$UserWorkspace, [string]$PreviousRoot) + $warnings = @() + # This runs only after installation succeeds. No scheduled housekeeping is created. + # Include older temp attempts, but never files still referenced by another process. + $root = Split-Path -Parent $Workspace + $processes = @(Get-CimInstance Win32_Process -ErrorAction Stop) + foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' })) { + try { + Assert-OfficeManagedPath $root $folder.FullName + if (!(Test-Path -LiteralPath (Join-Path $folder.FullName 'options.json'))) { continue } + if (@($processes | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($folder.FullName, [StringComparison]::OrdinalIgnoreCase) -ge 0 }).Count) { + $warnings += "$($folder.FullName) is still in use." + continue + } + Remove-OfficeManagedItem $root $folder.FullName + } catch { + $warnings += "$($folder.FullName): $($_.Exception.Message)" + Write-Error "Could not remove temporary deployment files: $($warnings[-1])" -ErrorAction Continue + } + } + # Earlier versions put downloads in ProgramData. Remove only their known staging + # artifacts after success; old user tasks may still need their helper/lock files. + if ($PreviousRoot -and $PreviousRoot -ne $root -and (Test-Path -LiteralPath $PreviousRoot)) { + foreach ($folder in @(Get-ChildItem -LiteralPath $PreviousRoot -Directory -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' })) { + try { + Assert-OfficeManagedPath $PreviousRoot $folder.FullName + if (!(Test-Path -LiteralPath (Join-Path $folder.FullName 'options.json'))) { continue } + if (@($processes | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($folder.FullName, [StringComparison]::OrdinalIgnoreCase) -ge 0 }).Count) { continue } + Remove-OfficeStagingFiles $PreviousRoot $folder.FullName + } catch { + $warnings += "$($folder.FullName): $($_.Exception.Message)" + Write-Error "Could not remove older deployment downloads: $($warnings[-1])" -ErrorAction Continue + } + } + } + if ($UserWorkspace -and $UserWorkspace -ne $Workspace) { + try { + # Start-OfficeUserCleanup already unregisters completed tasks. Preserve the + # helper whenever any task remains, including a failed unregister attempt. + $id = Split-Path -Leaf $UserWorkspace + $tasks = @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -like "Emberkom-OfficeCleanup-$id-*" }) + if (!$tasks.Count) { Remove-OfficeManagedItem (Split-Path -Parent $UserWorkspace) $UserWorkspace } + } catch { + $warnings += "$UserWorkspace : $($_.Exception.Message)" + Write-Error "Could not remove completed user cleanup files: $($warnings[-1])" -ErrorAction Continue + } + } + return ,$warnings +} + +function Get-OfficeMediaCacheKey { + param($Options) + $definitions = Get-OfficeDeploymentDefinitions + # Company, activation, app shutdown, and reboot choices affect XML, not the payload. + $contract = [ordered]@{ + Schema=1; Product=$Options.ProductId; Architecture=$Options.OfficeArchitecture + Channel=$Options.UpdateChannel; Language=$definitions.Language + OdtPage=$definitions.OdtPage; ExcludedApps=$definitions.OdtExcludedApps + Downloads=@(Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams | ForEach-Object { "$($_.Name)|$($_.File)|$($_.Uri)" }) + } + $sha = [Security.Cryptography.SHA256]::Create() + try { ([BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes(($contract | ConvertTo-Json -Depth 5 -Compress))))).Replace('-', '') } + finally { $sha.Dispose() } +} + +function Save-OfficeMediaCache { + param($Options, $Media, [string]$Workspace, [string]$CreatedUtc = ([DateTime]::UtcNow.ToString('o'))) + $root = Split-Path -Parent $Workspace + $files = @() + foreach ($name in @('ODT', 'odt.exe') + @(Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams | ForEach-Object { $_.File })) { + foreach ($file in @(Get-OfficeManagedFiles $root (Join-Path $Workspace $name))) { + $files += [pscustomobject]@{ Path=$file.FullName.Substring($Workspace.TrimEnd('\').Length + 1); Length=$file.Length; Hash=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256 -ErrorAction Stop).Hash } + } + } + [ordered]@{ Schema=1; Key=(Get-OfficeMediaCacheKey $Options); CreatedUtc=$CreatedUtc; Version=$Media.Version; Files=$files } | + ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $Workspace 'media-cache.json') -Encoding UTF8 -ErrorAction Stop +} + +function Restore-OfficeMediaCache { + param($Options, [string]$Workspace) + $root = Split-Path -Parent $Workspace + $definitions = Get-OfficeDeploymentDefinitions + $key = Get-OfficeMediaCacheKey $Options + foreach ($candidate in @(Get-ChildItem -LiteralPath $root -Directory -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' -and $_.FullName -ne $Workspace } | Sort-Object LastWriteTimeUtc -Descending)) { + $manifestPath = Join-Path $candidate.FullName 'media-cache.json' + if (!(Test-Path -LiteralPath $manifestPath)) { continue } + $inUse = @(Get-CimInstance Win32_Process -ErrorAction Stop | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($candidate.FullName, [StringComparison]::OrdinalIgnoreCase) -ge 0 }) + if ($inUse.Count) { throw "A previous Office deployment still has active processes using $($candidate.FullName). Wait for them to finish before retrying." } + try { + Assert-OfficeManagedPath $root $manifestPath + $manifest = Get-Content -LiteralPath $manifestPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop + $created = [DateTime]::Parse($manifest.CreatedUtc).ToUniversalTime() + if ($manifest.Schema -ne 1 -or $manifest.Key -ne $key -or $created -gt [DateTime]::UtcNow -or $created -lt [DateTime]::UtcNow.AddDays(-$definitions.MediaCacheDays)) { continue } + if ($manifest.Version -notmatch $definitions.OfficeBuildPattern -or !$manifest.Files.Count) { throw 'Invalid cache manifest.' } + $names = @('ODT', 'odt.exe') + @(Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams | ForEach-Object { $_.File }) + foreach ($entry in $manifest.Files) { + if ([IO.Path]::IsPathRooted($entry.Path) -or $entry.Path -match '(^|[\\/])\.\.([\\/]|$)' -or ($entry.Path -split '[\\/]')[0] -notin $names) { throw 'Invalid cached file path.' } + $path = Join-Path $candidate.FullName $entry.Path + Assert-OfficeManagedPath $candidate.FullName $path + $file = Get-Item -LiteralPath $path -ErrorAction Stop + if ($file.Length -ne $entry.Length -or (Get-FileHash -LiteralPath $path -Algorithm SHA256 -ErrorAction Stop).Hash -ne $entry.Hash) { throw "Cached file changed: $path" } + } + # Verify every executable we will launch, in addition to the cached hashes. + foreach ($name in @('odt.exe', 'ODT\setup.exe') + @(Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams | ForEach-Object { $_.File })) { + Assert-OfficeMicrosoftSignature (Join-Path $candidate.FullName $name) + } + $actualFiles = @(foreach ($name in $names) { Get-OfficeManagedFiles $root (Join-Path $candidate.FullName $name) }) + $actualPaths = @($actualFiles | ForEach-Object { $_.FullName.Substring($candidate.FullName.Length + 1) } | Sort-Object -Unique) + $expectedPaths = @($manifest.Files.Path | Sort-Object -Unique) + if ($actualFiles.Count -ne $manifest.Files.Count -or (Compare-Object $actualPaths $expectedPaths)) { throw 'Cached file inventory changed.' } + } catch { + $null = Write-Output "Ignoring unusable Office cache in $($candidate.FullName): $($_.Exception.Message)" + continue + } + # Transfer rather than duplicate several GB. Each deployment still has a new ID, + # so old per-user completion markers cannot suppress a new cleanup request. + foreach ($name in $names) { + $source = Join-Path $candidate.FullName $name; $destination = Join-Path $Workspace $name + Assert-OfficeManagedPath $root $source; Assert-OfficeManagedPath $root $destination + if (Test-Path -LiteralPath $destination) { throw "Cache destination already exists: $destination" } + Move-Item -LiteralPath $source -Destination $destination -ErrorAction Stop + } + Remove-OfficeManagedItem $root $manifestPath + $null = Write-Output "Reusing verified Office $($manifest.Version) media from $($candidate.FullName)." + return $manifest + } +} + function Assert-OfficeMicrosoftSignature { param([string]$Path) $signature = Get-AuthenticodeSignature -LiteralPath $Path -ErrorAction Stop @@ -163,12 +359,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 +386,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 { @@ -231,12 +450,44 @@ function New-OfficeConfiguration { return ,$xml } +function New-OfficeRemovalConfiguration { + param($Options) + $xml = New-Object Xml.XmlDocument + $configuration = $xml.CreateElement('Configuration'); $null = $xml.AppendChild($configuration) + $remove = $xml.CreateElement('Remove'); $remove.SetAttribute('All', 'TRUE'); $null = $configuration.AppendChild($remove) + $display = $xml.CreateElement('Display'); $display.SetAttribute('Level', 'None'); $display.SetAttribute('AcceptEULA', 'TRUE'); $null = $configuration.AppendChild($display) + $property = $xml.CreateElement('Property'); $property.SetAttribute('Name', 'FORCEAPPSHUTDOWN') + $property.SetAttribute('Value', $(if ($Options.OfficeAppShutdown -eq 'Force') { 'TRUE' } else { 'FALSE' })); $null = $configuration.AppendChild($property) + # Remove applies to Click-to-Run. RemoveMSI belongs to the installation configuration: + # ODT removes MSI Office before installing the replacement product in that operation. + return ,$xml +} + 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 + # Always refresh the small helper from this repository, even when using cached media. + $helper = Join-Path $Workspace 'Office-UserCleanup.ps1' + Save-OfficeDownload "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1" $helper + $tokens = $null; $errors = $null + $null = [Management.Automation.Language.Parser]::ParseFile($helper, [ref]$tokens, [ref]$errors) + if ($errors.Count -or !(Select-String -LiteralPath $helper -SimpleMatch $definitions.HelperVersion -Quiet)) { throw 'Office user cleanup helper is invalid; publish it with this installer.' } + $cached = Restore-OfficeMediaCache $Options $Workspace + if ($cached) { + $odtFolder = Join-Path $Workspace 'ODT' + $configPath = Join-Path $Workspace 'install.xml'; $removalPath = Join-Path $Workspace 'remove.xml' + $config = New-OfficeConfiguration $Options $odtFolder $cached.Version; $config.Save($configPath) + $removal = New-OfficeRemovalConfiguration $Options; $removal.Save($removalPath) + $companions = @{} + foreach ($download in (Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams)) { $companions[$download.Name] = Join-Path $Workspace $download.File } + # Preserve the original expiry; repeated validation must not keep old media forever. + $cached | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $Workspace 'media-cache.json') -Encoding UTF8 -ErrorAction Stop + return [pscustomobject]@{ Setup=(Join-Path $odtFolder 'setup.exe'); RemovalConfig=$removalPath; Config=$configPath; Helper=$helper; Version=$cached.Version; Companions=$companions; CachedMediaReused=$true } + } + $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 @@ -245,27 +496,18 @@ function Initialize-OfficeMedia { $code = Invoke-OfficeProcess $package "/quiet /extract:`"$odtFolder`"" (Join-Path $Workspace 'odt-extract') if ($code -ne 0) { throw "ODT extraction failed ($code)." } $setup = Join-Path $odtFolder 'setup.exe'; Assert-OfficeMicrosoftSignature $setup - # Microsoft's evergreen Get Help link retains its historical SaRA name. - $scrubZip = Join-Path $Workspace 'GetHelp.zip' - Save-OfficeDownload $definitions.GetHelpUrl $scrubZip - $scrubFolder = Join-Path $Workspace 'GetHelp' - $null = Write-Output "Extracting Get Help: $scrubZip -> $scrubFolder" - # Tools.ps1 overrides Expand-Archive with a Path-only wrapper. Use the PS 5.1 - # module explicitly for literal paths, while keeping diagnostics in the Tools log. - Microsoft.PowerShell.Archive\Expand-Archive -LiteralPath $scrubZip -DestinationPath $scrubFolder -ErrorAction Stop - $scrub = @(Get-ChildItem -LiteralPath $scrubFolder -Filter $definitions.GetHelpExecutable -File -Recurse) - if ($scrub.Count -ne 1) { throw "Microsoft download did not contain exactly one $($definitions.GetHelpExecutable)." } - Assert-OfficeMicrosoftSignature $scrub[0].FullName - # Run-Script only downloads the core file, so stage its helper explicitly. - $helper = Join-Path $Workspace 'Office-UserCleanup.ps1' - Save-OfficeDownload "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1" $helper - $tokens = $null; $errors = $null - $null = [Management.Automation.Language.Parser]::ParseFile($helper, [ref]$tokens, [ref]$errors) - if ($errors.Count -or !(Select-String -LiteralPath $helper -SimpleMatch $definitions.HelperVersion -Quiet)) { throw 'Office user cleanup helper is invalid; publish it with this installer.' } + $removalPath = Join-Path $Workspace 'remove.xml' + $removal = New-OfficeRemovalConfiguration $Options; $removal.Save($removalPath) $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.' } @@ -275,7 +517,9 @@ function Initialize-OfficeMedia { } $config.Configuration.Add.SetAttribute('Version', $versions[0].Name); $config.Save($configPath) $companions = Initialize-OfficeCompanionMedia $Workspace -InstallTeams $Options.InstallTeams - [pscustomobject]@{ Setup = $setup; Scrubber = $scrub[0].FullName; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions } + $media = [pscustomobject]@{ Setup = $setup; RemovalConfig = $removalPath; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions; CachedMediaReused=$false } + Save-OfficeMediaCache $Options $media $Workspace + $media } function Get-OfficeRunningApps { @@ -288,7 +532,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 +598,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 +612,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 @@ -401,28 +651,58 @@ function Get-OfficeSuiteInventory { $_.DisplayName -match '(?i)^(Microsoft\s+)?(365|Office|Visio|Project|Access|Word|Excel|Outlook|PowerPoint|OneNote|Publisher|Skype for Business)(\s|$)' -and $_.DisplayName -notmatch '(?i)(Add-in|Addin|Redistributable|Database Engine|Extensibility|Update|Hotfix|Click-to-Run)' } - $c2r = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration' -ErrorAction SilentlyContinue - if ($c2r.ProductReleaseIds) { [pscustomobject]@{ DisplayName = "Click-to-Run: $($c2r.ProductReleaseIds)" } } -} - -function Assert-OfficeScrubResult { - param([int]$ExitCode, [string]$Output, [object[]]$RemainingOffice) - # Microsoft's scenario output is checked separately from the process exit code. - $definitions = Get-OfficeDeploymentDefinitions - $results = [regex]::Matches($Output, $definitions.ScrubScenarioPattern) - if (!$results.Count) { throw "Get Help returned no recognizable scenario result (process exit $ExitCode). Check scrub logs." } - $result = $results[$results.Count - 1].Groups[1].Value - if ($result -notin $definitions.ScrubScenarioSuccess -or $ExitCode -notin $definitions.ScrubExitSuccess) { throw "Get Help removal failed: scenario $result, process $ExitCode. Check scrub logs." } - if (@($RemainingOffice).Count) { throw "Office remains after cleanup: $(($RemainingOffice | ForEach-Object { $_.DisplayName }) -join '; '). Reboot/repair and rerun; installation stopped." } + $key = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration' + if (Test-Path -LiteralPath $key -ErrorAction Stop) { + $c2r = Get-ItemProperty -LiteralPath $key -ErrorAction Stop + if ($c2r.ProductReleaseIds) { [pscustomobject]@{ DisplayName = "Click-to-Run: $($c2r.ProductReleaseIds)" } } + } } function Remove-OfficeSuite { param($Media, [string]$Workspace) - $null = Write-Output 'Removing Office, including Visio and Project, with Microsoft Get Help.' - $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 @(Get-OfficeSuiteInventory) + # 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. + $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 '; ')." } + if (!@($existing | Where-Object { $_.WindowsInstaller -ne 1 }).Count) { + $null = Write-Output 'No non-MSI Office products detected; skipping the separate ODT removal pass.' + return 0 + } + 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 Visio and Project, with ODT.' + $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 -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 0 +} + +function Test-OfficeCanDeferRestart { + param($Options, [ValidateSet('Office', 'Companions')][string]$Stage) + if ($Options.DeferReboot -isnot [bool]) { throw 'DeferReboot must be a validated Boolean before deciding whether to continue.' } + if (!$Options.DeferReboot) { + $null = Write-Output "$Stage removal requested a restart. DeferReboot=false; stopping before replacement installation." + return $false + } + # A 3010 result is success with a restart pending, not permission to ignore + # incomplete removal. Verify the old products are gone before deferring it. + $verified = Wait-OfficeResult { + if ($Stage -eq 'Office') { return @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 }).Count -eq 0 } + @(Get-OfficeMachineCompanionEntries).Count -eq 0 + } "$Stage removal before deferring its restart" + if ($verified) { + $null = Write-Output "$Stage removal verified. Deferring the requested restart until after deployment; the final result will retain exit code 3010." + return $true + } + $remaining = @(if ($Stage -eq 'Office') { Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 } } else { Get-OfficeMachineCompanionEntries }) + $null = Write-Output "Cannot defer the $Stage removal restart: registrations remain for $($remaining.DisplayName -join '; '). Restart and rerun before replacement installation." + return $false } function Get-OfficeAppxNames { @@ -443,25 +723,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 +820,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 removal/installation has not started." } + } $reboot } @@ -547,7 +901,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 @@ -555,11 +912,24 @@ function Start-OfficeUserCleanup { 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). Media and logs remain in $Workspace." } - $installed = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration' -ErrorAction Stop + if ($code -notin @(0, 3010)) { throw "Office installation failed (exit $code). Media and logs remain in $Workspace. If old Office needs repair, arrange an attended manual scrub: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl). No interactive scrubber was launched." } + $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)" + } $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.' } + # Microsoft requires a restart to finish MSI removal even when setup doesn't enforce it. + if ($msi.Count) { $null = Write-Output 'Legacy MSI Office removal was verified. A restart is required to finish removal; no automatic reboot was requested.'; return 3010 } $code } @@ -569,6 +939,7 @@ function Invoke-OfficeDeployment { # Internal action messages use Tools.ps1's logger. Suppress its echoed success output # so it cannot become part of a function's return value. Entry prints the Syncro receipt. if ($Options.ValidateBeforeChanges -isnot [bool]) { throw 'ValidateBeforeChanges must be a validated Boolean before running the workload.' } + if ($Options.DeferReboot -isnot [bool]) { throw 'DeferReboot must be a validated Boolean before running the workload.' } Assert-OfficeDeploymentHost $Options $mutex = New-Object Threading.Mutex($false, 'Global\EmberkomOfficeDeployment') $locked = $false @@ -578,8 +949,9 @@ function Invoke-OfficeDeployment { $runningApps = @(Get-OfficeRunningApps | Select-Object -ExpandProperty ProcessName -Unique) if ($runningApps.Count -and $Options.OfficeAppShutdown -eq 'Abort') { throw "Apps are running: $($runningApps -join ', '). Close them or select OfficeAppShutdown=Force for the maintenance window." } $workspace = New-OfficeWorkspace - $null = Write-Output "Office request: $($Options.OfficeSubscription) / $($Options.ProductId), $($Options.OfficeArchitecture)-bit, $($Options.UpdateChannel), ValidateBeforeChanges=$($Options.ValidateBeforeChanges). Workspace: $workspace" + $null = Write-Output "Office request: $($Options.OfficeSubscription) / $($Options.ProductId), $($Options.OfficeArchitecture)-bit, $($Options.UpdateChannel), ValidateBeforeChanges=$($Options.ValidateBeforeChanges), DeferReboot=$($Options.DeferReboot). Workspace: $workspace" $Options | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $workspace 'options.json') -Encoding UTF8 + $root = Split-Path -Parent $workspace $profiles = @(Get-CimInstance Win32_UserProfile -ErrorAction Stop | Where-Object { !$_.Special -and $_.LocalPath }) # Unavailable containers/roaming profiles must not silently disappear from the cleanup report. foreach ($profile in $profiles) { @@ -588,34 +960,49 @@ function Invoke-OfficeDeployment { $media = Initialize-OfficeMedia $Options $workspace if ($Options.ValidateBeforeChanges) { $existingOffice = @(Get-OfficeSuiteInventory | ForEach-Object { $_.DisplayName }) - $null = Write-Output 'Validation passed. Stopped before closing apps, uninstalling, clearing identities, registering tasks, or installing.' + # This helper is refreshed on every run; validation does not need to retain it. + Remove-OfficeManagedItem $root $media.Helper + $null = Write-Output 'Validation passed. Stopped before closing apps, uninstalling, clearing identities, registering user cleanup tasks, or installing.' return [pscustomobject]@{ OfficeDeploymentStatus='ValidationPassed'; ExitCode=0; ValidateBeforeChanges=$true ProductId=$Options.ProductId; OfficeVersion=$media.Version; Architecture=$Options.OfficeArchitecture - UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams + UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams; OfficeRemovalMethod='SilentODT'; DeferReboot=$Options.DeferReboot Workspace=$workspace; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps - NextStep='Set ValidateBeforeChanges=false to deploy. That run repeats validation and downloads fresh media.' + CachedMediaReused=[bool]$media.CachedMediaReused; MediaCacheDays=(Get-OfficeDeploymentDefinitions).MediaCacheDays + NextStep='Set ValidateBeforeChanges=false to deploy. Matching unexpired media is verified and reused; prerequisites are checked again.' } } Stop-OfficeDeploymentApps $Options $reboot = Remove-OfficeCompanionApps $workspace - if ($reboot) { + if ($reboot -and !(Test-OfficeCanDeferRestart $Options 'Companions')) { $null = Write-Output 'Companion app removal requires a restart. Restart and rerun; Office installation has not started.' - return [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; Workspace = $workspace; PendingUserSids = @() } + return [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'CompanionRemoval'; Workspace = $workspace; PendingUserSids = @() } + } + $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.' + return [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @() } } - Remove-OfficeSuite $media $workspace foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile } - $pending = Start-OfficeUserCleanup $profiles $media $workspace - Set-OfficeReinstallPhase $workspace + $userWorkspace = $workspace + if ($profiles.Count) { $userWorkspace = New-OfficeUserWorkspace $media $workspace } + $pending = Start-OfficeUserCleanup $profiles $media $userWorkspace + Set-OfficeReinstallPhase $userWorkspace $code = Install-OfficeMedia $Options $media $workspace $companions = Install-OfficeCompanionApps $media.Companions $workspace -InstallTeams $Options.InstallTeams - if ($companions.ExitCode -eq 3010) { $code = 3010 } + if ($reboot -or $removalCode -eq 3010 -or $companions.ExitCode -eq 3010) { $code = 3010 } $status = if ($pending.Count) { 'InstalledWithUserCleanupPending' } else { 'Installed' } - $null = Write-Output "$status. Office $($media.Version), $($Options.ProductId). Restart after the Office scrub is recommended; no automatic reboot was requested." + $null = Write-Output "$status. Office $($media.Version), $($Options.ProductId). No automatic reboot was requested." $provisionedApps = if ($Options.InstallTeams) { 'Teams and new Outlook are' } else { 'New Outlook is' } $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.' - [pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if ($pending.Count -and $code -eq 0) { 2 } else { $code }); ValidateBeforeChanges=$false; Workspace = $workspace; PendingUserSids = $pending; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version } + $cleanupWarnings = @() + try { + $cleanupWarnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace -PreviousRoot (Join-Path $env:ProgramData 'EmberkomOfficeDeployment') + } + catch { $cleanupWarnings = @($_.Exception.Message); Write-Error "Office deployment file cleanup was incomplete: $($cleanupWarnings[0])" -ErrorAction Continue } + if ($cleanupWarnings.Count) { $null = Write-Output 'Installation succeeded, but some deployment files remain; see the diagnostic log.' } + [pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if ($pending.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; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version; CachedMediaReused=[bool]$media.CachedMediaReused; ArtifactCleanupPending=($cleanupWarnings.Count -gt 0) } } finally { if ($locked) { $mutex.ReleaseMutex() } $mutex.Dispose() @@ -669,9 +1056,9 @@ function Invoke-OfficeDeploymentEntry { } $null = Write-Output "Office deployment host: Windows PowerShell $($PSVersionTable.PSVersion), $([IntPtr]::Size * 8)-bit." if ($options.ValidateBeforeChanges) { - Microsoft.PowerShell.Utility\Write-Output 'Validation only: checking prerequisites and staging current installers/Office media (several GB). No app shutdown, cleanup, or installation will run.' + Microsoft.PowerShell.Utility\Write-Output 'Validation only: checking prerequisites and verifying cached media or staging current installers (several GB). No app shutdown, Office/user cleanup, or installation will run.' } else { - Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: validating and staging media, then removing and reinstalling Office and the selected companion apps.' + Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: validating and staging media, then silently removing Office with ODT and reinstalling Office and the selected companion apps.' } Microsoft.PowerShell.Utility\Write-Output "Diagnostic log: $Global:LogFile" $results = @(Invoke-OfficeDeployment -Options $options) @@ -682,13 +1069,15 @@ function Invoke-OfficeDeploymentEntry { $null = Write-Output $receipt Microsoft.PowerShell.Utility\Write-Output $receipt if ($deployment[0].OfficeDeploymentStatus -like 'Installed*') { - Microsoft.PowerShell.Utility\Write-Output 'Restart after the Office scrub is recommended. Users may need to sign out and back in for companion app registration; check PendingUserSids for deferred cleanup.' + if ($deployment[0].ArtifactCleanupPending) { Microsoft.PowerShell.Utility\Write-Output 'WARNING: Installation succeeded, but some deployment files could not be cleaned up. See the diagnostic log; no background cleanup is scheduled.' } + if ($deployment[0].ExitCode -eq 3010) { Microsoft.PowerShell.Utility\Write-Output 'A restart is required to finish deployment; no automatic reboot was requested.' } + Microsoft.PowerShell.Utility\Write-Output 'Users may need to sign out and back in for companion app registration; check PendingUserSids for deferred cleanup.' } $ExitCode.Value = [int]$deployment[0].ExitCode } $OfficeInputValues = @{} -foreach ($OfficeInputName in @('OfficeSubscription', 'OfficeArchitecture', 'UpdateChannel', 'OfficeActivation', 'OfficeAppShutdown', 'ValidateBeforeChanges', 'COMPANY')) { +foreach ($OfficeInputName in @('OfficeSubscription', 'OfficeArchitecture', 'UpdateChannel', 'OfficeActivation', 'OfficeAppShutdown', 'DeferReboot', 'ValidateBeforeChanges', 'COMPANY')) { $OfficeInputVariable = Get-Variable -Name $OfficeInputName -ErrorAction SilentlyContinue $OfficeInputValues[$OfficeInputName] = if ($null -ne $OfficeInputVariable) { [string]$OfficeInputVariable.Value } else { '' } } diff --git a/Uninstall-MicrosoftOffice.ps1 b/Uninstall-MicrosoftOffice.ps1 index ad27775..da77867 100644 --- a/Uninstall-MicrosoftOffice.ps1 +++ b/Uninstall-MicrosoftOffice.ps1 @@ -19,19 +19,23 @@ End-Process -Name 'Teams' -Match -Force # URL to the OffscrubC2R.vbs script $UninstallScriptURL = 'https://github.com/OfficeDev/Office-IT-Pro-Deployment-Scripts/raw/master/Office-ProPlus-Deployment/Deploy-OfficeClickToRun/OffScrubc2r.vbs' -# The path to the local script once downloaded -$UninstallScript = Download-File -URL $UninstallScriptURL +# Use an owned, unique file so partial downloads can also be removed in finally. +$UninstallScript = Join-Path (Get-TempPath) ('OfficeUninstall-' + [guid]::NewGuid().ToString('N') + '.vbs') # Args to pass to the OffscrubC2R.vbs script $ScriptArgs = "/ALL /QUIET /NOCANCEL" -# Run the script -Write-Output "Uninstalling all Click2Run versions of Office" -Try { Start-Process "cscript.exe" -ArgumentList "//nologo ""${UninstallScript}"" ${ScriptArgs}" -Wait } -Catch { Write-Error $_.Exception.Message } - -# Delete the downloaded script -If ( Test-Path $UninstallScript ) { - Write-Output "Deleting downloaded script: ""${UninstallScript}""" - Remove-Item -Path $UninstallScript -Force -ErrorAction SilentlyContinue -} \ No newline at end of file +try { + $null = Download-File -URL $UninstallScriptURL -File $UninstallScript + Write-Output 'Uninstalling all Click2Run versions of Office' + Start-Process 'cscript.exe' -ArgumentList "//nologo `"$UninstallScript`" $ScriptArgs" -Wait -WindowStyle Hidden -ErrorAction Stop +} catch { + Write-Error $_.Exception.Message -ErrorAction Continue + throw +} finally { + if (Test-Path -LiteralPath $UninstallScript -PathType Leaf) { + Write-Output "Deleting downloaded script: $UninstallScript" + try { Remove-Item -LiteralPath $UninstallScript -Force -ErrorAction Stop } + catch { Write-Error "Could not delete $UninstallScript : $($_.Exception.Message)" -ErrorAction Continue } + } +} diff --git a/docs/Office365-Deployment.md b/docs/Office365-Deployment.md index 32bee22..198bc7d 100644 --- a/docs/Office365-Deployment.md +++ b/docs/Office365-Deployment.md @@ -6,8 +6,8 @@ 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. -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. +1. Publish `Install-MicrosoftOffice365.ps1` and `resources/office/Office-UserCleanup.ps1` together in the public repository. The installer requires helper version `EmberkomOfficeUserCleanup-v4`, 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** and set the execution limit to **120 minutes (2 hours)**. PowerShell 7 is not required or launched. Allow 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. Syncro's limit covers the entire run, including downloads, cleanup, and 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. @@ -19,6 +19,7 @@ The selection identifies the client's purchased subscription; it does not discov | `UpdateChannel` | `Current`, `MonthlyEnterprise`, `SemiAnnual` | `Current` | | `OfficeActivation` | `User`, `SharedComputer` | `User` | | `OfficeAppShutdown` | `Abort`, `Force` | `Abort` | +| `DeferReboot` | `true`, `false` | `true` | All variables configured in Syncro must have a nonempty value. Set the dropdown defaults above in Syncro; the shim reads the injected strings without assigning over them. `Select a subscription` is a nonempty placeholder that the main script rejects before deployment. @@ -28,6 +29,8 @@ Syncro supplies `COMPANY` automatically with the endpoint's company name in this `Abort` stops if an Office app, Teams, OneDrive, or new Outlook is running. `Force` closes them across all sessions after staging succeeds; unsaved work can be lost. Choose Force only for the intended maintenance window. Deferred cleanup also closes that user's classic Teams when removing it at sign-in. +`DeferReboot=true` (default) attempts to finish deployment in one run. When an uninstaller returns `3010`, the script waits for removal verification; if the old products are gone, it continues and carries the restart requirement into the final receipt. If removal cannot be verified, it returns `RestartRequiredBeforeInstall` even with `true` selected. `DeferReboot=false` returns that status immediately when an Office or companion uninstaller requests a restart. Neither choice restarts Windows or schedules a reboot. The main script parses the injected string using `ConvertTo-RmmBoolean` from Tools.ps1; missing/null/blank input defaults to `true`, invalid values fail validation, and receipts contain a JSON Boolean. Configure this dropdown in Syncro; the shim still only forwards injected strings through `Run-Script`. + `Auto` selects 64-bit Office on 64-bit Windows and 32-bit otherwise. Select `32` only for required add-in compatibility on supported x86/x64 systems. ARM64 rejects 32-bit Office. Companion installers follow the Windows architecture independently of Office bitness. The main repository script relaunches a 32-bit Syncro host into native Windows PowerShell 5.1 via `Sysnative` on 64-bit Windows, preserving the injected strings. All scheduled user cleanup also uses `powershell.exe`. The RMM shim contains no deployment or relaunch logic. Before removal, the script checks the apps' minimum OS requirements: Windows build 19041 or newer; Windows Server requires at least 2022 build 20348.2402 for new Outlook. Windows 10 LTSC is rejected when Teams is selected. These checks do not replace checking current Office/Windows support and the additional requirements of an RDS/AVD deployment. @@ -51,21 +54,21 @@ The E3/E5 selections are consolidated because those plans use the same Office pr All selections install new Outlook and OneDrive. Teams is downloaded and installed only for `Microsoft 365 Business Standard`, `Microsoft 365 Business Premium`, and `Microsoft/Office 365 E3/E5` (including their accepted legacy enterprise aliases). Every `(no Teams)` selection and both standalone `Microsoft 365 Apps for business` / `Microsoft 365 Apps for enterprise` selections skip the Teams download, installation, and installed-version verification. ODT also explicitly excludes Teams, so it cannot bypass this selection. Existing Teams installations are still removed during cleanup. Installing a client does not purchase/assign service entitlements; users must have the appropriate account and services to use it. -Business Basic, E1, frontline/web-only plans, education/government variants, consumer subscriptions, and perpetual Office/LTSC editions are not deployment selections in this script. Missing or unsupported selections stop before downloads or removal. Existing perpetual Office installations can be removed by the scrubber; that does not authorize installing Microsoft 365 without its license. +Business Basic, E1, frontline/web-only plans, education/government variants, consumer subscriptions, and perpetual Office/LTSC editions are not deployment selections in this script. Missing or unsupported selections stop before downloads or removal. Existing perpetual Click-to-Run installations, including retail Office 2019/2021, are targeted by ODT's removal pass; supported older MSI editions are removed during installation as described below. That does not authorize installing Microsoft 365 without its license. `SharedComputer` enables shared computer activation. Business Standard and standalone Apps for business are rejected for this mode; Business Premium and the listed eligible enterprise plans are accepted. Confirm the users' entitlements and host support, especially on RDS/AVD. See [Microsoft's shared activation requirements](https://learn.microsoft.com/en-us/microsoft-365-apps/licensing-activation/overview-shared-computer-activation). ## Download, removal, and installation -With `ValidateBeforeChanges=true`, the script checks the subscription/activation combination, host and OS prerequisites, running apps, and availability of registered user profiles. It downloads and verifies ODT, Get Help, the user cleanup helper, the full Office payload, and the selected companion bootstrappers. It writes the XML/options and returns `ValidationPassed` with the selected product, version, company, Teams choice, existing Office inventory, and running apps. It does **not** close apps, uninstall, clear identity/credentials, load user hives, register cleanup tasks, or install apps. `OfficeAppShutdown=Force` only reports running apps in this mode; `Abort` fails validation if any are running. +With `ValidateBeforeChanges=true`, the script checks the subscription/activation combination, host and OS prerequisites, running apps, and availability of registered user profiles. It downloads and verifies ODT, the user cleanup helper, the full Office payload, and the selected companion bootstrappers. It writes the installation/removal XML and options, and returns `ValidationPassed` with `OfficeRemovalMethod=SilentODT`, the selected product, version, company, Teams choice, existing Office inventory, and running apps. It does **not** close apps, uninstall, clear identity/credentials, load user hives, register per-user cleanup tasks, or install apps. `OfficeAppShutdown=Force` only reports running apps in this mode; `Abort` fails validation if any are running. -Validation writes logs and staging files, secures its workspace, and runs ODT extraction and `/download`; it is not a zero-write inventory scan. Allow several GB and the same download time as deployment. A later `false` run downloads fresh media and repeats the checks. Validation does not prove tenant entitlements, successful future uninstallation/activation, or availability of the online companion payloads at install time. +Validation writes logs and staging files in the execution account's temp directory, secures its workspace, and runs ODT extraction and `/download` when no reusable cache exists; it is not a zero-write inventory scan. Allow several GB for the first run. It registers no scheduled tasks. A later `false` run repeats prerequisites and reuses matching, unexpired media after verifying its SHA-256 hashes and Microsoft executable signatures. The small user cleanup helper is always refreshed from the repository and is deleted from the validation workspace before returning. Validation does not prove tenant entitlements, successful future uninstallation/activation, or availability of the online companion payloads at install time. 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. -The [Get Help command-line package](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-command-line-overview) is downloaded fresh and its executable signature checked. Microsoft's evergreen link still uses the historical name `https://aka.ms/SaRA_EnterpriseVersionFiles`. The script executes `GetHelpCmd.exe`, not retired `SaRAcmd.exe`. +**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 downloads the current build in the selected channel first. Installation is pinned to that local build, uses English (`en-us`), enables updates, and uses `Display Level="None"`. The [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options) describes these settings. Existing update policies can subsequently override the chosen channel. +On a cache miss, ODT downloads the current build in the selected channel. A cache hit uses the build validated earlier, for at most seven days from the original download; it does not check for a newer build during that interval. Installation is pinned to that local build, uses English (`en-us`), enables updates, and uses `Display Level="None"`. The [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options) describes these settings. Existing update policies can subsequently override the chosen channel. The companion apps remain excluded from ODT because the main script installs the selected companions explicitly for all users after Office. Their installers are downloaded from Microsoft's evergreen links and their Microsoft Authenticode signatures checked before any removal; Teams is staged only when the subscription includes it. Teams, new Outlook, and WebView2 use online bootstrappers: only their installer executables are staged, and their payload downloads can still fail later. The complete Office suite payload is staged before removal. @@ -80,7 +83,23 @@ These follow Microsoft's deployment guidance for [Teams](https://learn.microsoft New Outlook, and Teams when selected, are provisioned for current and future users; users may need to sign out and back in for registration. OneDrive installs per-machine and handles migration of existing user accounts. App account setup and any tenant policy prompts are separate from the silent installation. The script does not switch the default mail application, force migration from classic Outlook, or configure OneDrive folder backup. -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. +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 skips this separate pass when only MSI Office, or no Office, is detected. See the [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options). + +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. + +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. + +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. +- Direct machine and per-user companion 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. This retry applies to `msiexec.exe`, not ODT's internal `RemoveMSI` operation. The script does not kill an unrelated installer or blindly repeat an Office removal or installation. +- After successful operations, machine removal and installation verification allow up to five minutes of polling for registry/package state to settle. The standalone user's Teams add-in verification retains its 60-second 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 @@ -88,11 +107,26 @@ The core script clears Office 15/16 identity/licensing registry keys and Office 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. -A deployment is reported as **InstalledWithUserCleanupPending** if any user task has not completed. Failed tasks also remain pending and retry on later sign-ins. The helper writes `Status=Complete` under `HKCU\Software\Emberkom\OfficeDeployment\` after success and then becomes a no-op. Tasks completed during deployment are removed automatically. Tasks that finish later remain registered; an administrator can confirm their marker/task result and unregister those exact tasks afterward. Do not delete their helper while any cleanup is pending. +A deployment is reported as **InstalledWithUserCleanupPending** if any user task has not completed. Failed tasks also remain pending and retry on later sign-ins. The helper writes `Status=Complete` under `HKCU\Software\Emberkom\OfficeDeployment\` after success and then becomes a no-op. Tasks completed during deployment are removed automatically. Tasks that finish later retain their previous behavior: they remain registered but do no further work after success. An administrator can confirm completion and remove those exact tasks and their helper afterward. There is no daily housekeeping task. + +The helper, lock, and reinstall marker for these previously agreed logon tasks live separately in `%ProgramData%\EmberkomOfficeDeployment\`, so routine temp cleanup cannot break deferred user cleanup. The receipt identifies this folder as `UserCleanupWorkspace`. If no user tasks remain at the end of a successful deployment, the script removes this helper folder too. It is the only deployment code intentionally retained for pending users; the main installer does not persist on the endpoint. + +## Temporary media and cleanup during deployment + +- A completed staging pass records a protected `media-cache.json` inventory with file hashes, version, original creation time, and a matching key derived from product, architecture, channel, language, and companion download definitions. Compatible runs move these installers into their new workspace instead of copying or redownloading them. This keeps each deployment's user cleanup ID separate. Company, activation, shutdown, and reboot selections are applied to freshly generated XML. The receipt reports `CachedMediaReused`. +- Downloads live under `EmberkomOfficeDeployment\` in `[IO.Path]::GetTempPath()` for the execution account. In Syncro this is SYSTEM's temp location, not the signed-in user's temp directory. The actual path is reported in `Workspace`. Folder permissions prevent standard users from changing executable content. +- Cached installers remain eligible for reuse for **seven days**, provided the files still exist. This is a freshness limit, not a scheduled deletion policy. Expired, incomplete, modified, unsigned, or incompatible caches are not reused. Changing to a no-Teams plan cannot reuse a Teams-enabled cache. A failed deployment or a stop for restart leaves media in temp for a retry. Repeated validation does not extend the original freshness limit. If routine temp cleanup purges it first, the next run downloads fresh media. +- Once Office and all selected companion apps are verified installed, the same script run deletes its entire temporary workspace, including the Office payload, ODT package/extraction, companion bootstrappers, cache manifest, helper copy, generated XML, and temporary process logs. It also removes unused older temporary deployment workspaces and known installer downloads from older ProgramData stages. Deferred-user files in ProgramData, installed applications, and Microsoft's servicing caches are preserved. +- There is **no daily housekeeping task, resident housekeeping script, or separate log-retention job**. Validation/failure leftovers are subject to the endpoint's existing temp-cleanup routines; exact deletion timing depends on those routines. File removal rejects junctions/symlinks and skips workspaces referenced by running processes. +- Cleanup failures do not change a verified installation into an installation failure. `ArtifactCleanupPending=true` and a console warning identify files left behind; there is no scheduled retry. A later successful deployment or the endpoint's ordinary temp cleanup can remove them. + +Earlier ProgramData caches are not searched for reuse in the new temp location. Their known installer files are still cleaned after a successful deployment, while existing user helpers and diagnostic files are preserved. An RMM hard termination can interrupt cleanup; leftovers remain in temp rather than depending on a new background process. ## Results and troubleshooting @@ -101,19 +135,23 @@ A deployment is reported as **InstalledWithUserCleanupPending** if any user task | `0` | `ValidationPassed`: validation only, no deployment performed. `Installed`: Office and companion installations verified; user cleanup completed for the enumerated profiles. | | `1` | Failure; inspect the error and logs. In deployment mode, removal may already have happened. | | `2` | Office and companion apps installed, but user cleanup is pending. Sign in as the listed users and inspect task results; do not repeatedly reinstall merely to check status. | -| `3010` | Restart required by an installer. Read `OfficeDeploymentStatus`: `RestartRequiredBeforeInstall` means restart then rerun; `Installed` or `InstalledWithUserCleanupPending` means Office and companions completed and an installer requested restart. Pending user SIDs can also be present. | +| `3010` | A restart is required. Read `OfficeDeploymentStatus`: `RestartRequiredBeforeInstall` means restart then rerun; `Installed` or `InstalledWithUserCleanupPending` means Office and companions completed with a restart deferred until afterward. `RestartRequired=true` and `DeferReboot` are included; a stop before installation also identifies `RestartStage`. Pending user SIDs can also be present. | -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. +Syncro may flag nonzero results as errors; read the printed status and pending SIDs. Schedule any required restart separately. The script also returns `3010` after verified legacy MSI Office removal, following Microsoft's restart requirement. + +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 removal, 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. +Process stdout/stderr logs, options, and generated XML are temporary files in the reported `Workspace`. They remain after a failed or validation-only run until a later successful deployment or routine temp cleanup removes them; they are deleted after successful installation. ODT removal uses `office-remove.stdout.log` / `.stderr.log` and `remove.xml`; installation uses `office-install.stdout.log` / `.stderr.log` and `install.xml`. The main Tools log retains the actions, results, and receipt and is not deleted. The separate limited-user cleanup task does not share the elevated Tools execution context; its small transcript remains in `%LOCALAPPDATA%\Emberkom\OfficeDeployment\.log` for each user. Do not manually delete `UserCleanupWorkspace` while its logon tasks are pending. + +The separate legacy `Uninstall-MicrosoftOffice.ps1` deletes its downloaded VBS in `finally`, including after a failed/partial download or launch error. It is not part of the modern installer workflow. Registry-only Office fixes do not stage installers, and RMM shims execute their downloaded PowerShell source in memory. The installer verifies the selected Office product, bitness, and downloaded version in Click-to-Run registration, plus selected companion deployment as listed above. The final receipt includes `CompanionApps` versions and `TeamsSelected`; when Teams is skipped, it has no installed version in that receipt. Any selected companion installer or verification failure fails the deployment, even if Office installed successfully. It does not claim that the subscription has activated. It does not delete mail profiles, revoke cloud sessions, or roll back a removed Office installation. ## 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. ODT removal tests cover silent XML, absent Office, mixed MSI/Click-to-Run installations, leftovers, read errors, MSI verification after installation, restart results, and absence of an interactive fallback. 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. Tests use a separate mutex and 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/rmm/Install-MicrosoftOffice365.ps1 b/rmm/Install-MicrosoftOffice365.ps1 index fa1e143..062645b 100644 --- a/rmm/Install-MicrosoftOffice365.ps1 +++ b/rmm/Install-MicrosoftOffice365.ps1 @@ -9,6 +9,9 @@ # [string]$UpdateChannel - Current (default), MonthlyEnterprise, SemiAnnual # [string]$OfficeActivation - User (default), SharedComputer # [string]$OfficeAppShutdown - Abort (default), Force (unsaved work can be lost) +# [string]$DeferReboot - true (default: continue after verified removal), false (stop on reboot request) +# The main script converts the injected string with ConvertTo-RmmBoolean. +# Neither choice automatically restarts Windows. Set Syncro's execution limit to 120 minutes. # Every variable configured in Syncro needs a nonempty value. Do not overwrite injected values. # Syncro also supplies [string]$COMPANY with the endpoint's company name. # It is passed through to Office setup; no company dropdown is needed. diff --git a/tests/Install-MicrosoftOffice365.Tests.ps1 b/tests/Install-MicrosoftOffice365.Tests.ps1 index 39bb330..a321044 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'." @@ -90,12 +179,25 @@ try { $values = @{ OfficeSubscription='Microsoft 365 E3' }; $values[$name]='invalid' Assert-OfficeThrows { Get-OfficeDeploymentOptions $values } "Invalid $name" } + foreach ($value in @($null, '', ' ', 'true', '$true', $true)) { + $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; DeferReboot=$value} + Assert-OfficeTest ($options.DeferReboot -is [bool] -and $options.DeferReboot) 'Missing/blank or true restart input must produce Boolean true.' + } + foreach ($value in @('false', '$false', $false, '0', ' No ')) { + $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; DeferReboot=$value} + Assert-OfficeTest ($options.DeferReboot -is [bool] -and !$options.DeferReboot) 'False restart text must be parsed, not cast to a truthy string.' + } + Assert-OfficeTest ((Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'}).DeferReboot) 'Omitted restart input must default to true.' + foreach ($value in @('maybe', 'Defer', 'StopBeforeInstall')) { + Assert-OfficeThrows { Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; DeferReboot=$value} } 'Invalid \$DeferReboot' + } $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeArchitecture='32'; COMPANY='A & B "quoted"'; OfficeActivation='SharedComputer'; OfficeAppShutdown='Force'} $xml = New-OfficeConfiguration $options 'C:\Office & Tools' '16.0.12345.67890' $roundTrip = [xml]$xml.OuterXml Assert-OfficeTest ($roundTrip.Configuration.AppSettings.Setup.Value -eq $options.Company) 'Company XML escaping failed.' Assert-OfficeTest ($roundTrip.Configuration.Add.SourcePath -eq 'C:\Office & Tools') 'Source XML escaping failed.' Assert-OfficeTest ($roundTrip.Configuration.Display.Level -eq 'None') 'Install must be silent.' + Assert-OfficeTest ($null -ne $roundTrip.SelectSingleNode('/Configuration/RemoveMSI') -and $null -ne $roundTrip.SelectSingleNode('/Configuration/Add')) 'Legacy MSI removal must run with the replacement installation.' Assert-OfficeTest ($roundTrip.Configuration.Add.OfficeClientEdition -eq '32') '32-bit selection ignored.' Assert-OfficeTest ($roundTrip.SelectSingleNode('//Property[@Name="SharedComputerLicensing"]').Value -eq '1') 'Shared activation lost.' Assert-OfficeTest ($roundTrip.Configuration.Add.Version -eq '16.0.12345.67890') 'Downloaded version must be pinned.' @@ -106,29 +208,30 @@ try { Assert-OfficeThrows { Assert-OfficeCompanionPlatform -Build 20348 -ProductType 3 -Revision 2401 } 'Server 2022' Assert-OfficeThrows { Assert-OfficeCompanionPlatform -Build 19044 -ProductType 1 -EditionId EnterpriseS -InstallTeams $true } 'LTSC' Assert-OfficeCompanionPlatform -Build 19044 -ProductType 1 -EditionId EnterpriseS -InstallTeams $false - # Exercise actual ZIP extraction in media staging under the Tools.ps1 command scope. + foreach ($shutdown in @('Abort','Force')) { + $removal = New-OfficeRemovalConfiguration ([pscustomobject]@{OfficeAppShutdown=$shutdown}) + Assert-OfficeTest ($removal.Configuration.Remove.All -eq 'TRUE' -and $removal.Configuration.Display.Level -eq 'None' -and $removal.Configuration.Display.AcceptEULA -eq 'TRUE') 'ODT removal must remove all Click-to-Run products without UI.' + Assert-OfficeTest ($removal.SelectSingleNode('//Property[@Name="FORCEAPPSHUTDOWN"]').Value -eq $(if ($shutdown -eq 'Force') {'TRUE'} else {'FALSE'})) 'Silent removal must honor the app shutdown selection.' + Assert-OfficeTest ($null -eq $removal.SelectSingleNode('/Configuration/Add') -and $null -eq $removal.SelectSingleNode('/Configuration/RemoveMSI')) 'The separate removal pass must not install Office or depend on standalone RemoveMSI.' + } + # Exercise media staging under the Tools.ps1 command scope, including literal paths. # Network requests, Microsoft signatures, and executable launches are mocked; files are inert. & { $archiveCommand = Get-Command Expand-Archive Assert-OfficeTest ($archiveCommand.CommandType -eq 'Function' -and !$archiveCommand.Parameters.ContainsKey('LiteralPath')) 'The real Tools archive override must be present for this regression.' $mediaWorkspace = Join-Path $testRoot 'media [literal]' $null = [IO.Directory]::CreateDirectory($mediaWorkspace) - $zipSource = Join-Path $testRoot 'zip-source' - $null = [IO.Directory]::CreateDirectory($zipSource) - [IO.File]::WriteAllText((Join-Path $zipSource 'GetHelpCmd.exe'), 'Inert scrubber fixture; never executed.') - $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') { - [IO.File]::Copy($mediaFixtureZip, $Path) + 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 'Office-UserCleanup.ps1') { [IO.File]::WriteAllText($Path, '# ' + (Get-OfficeDeploymentDefinitions).HelperVersion) } else { @@ -146,6 +249,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.') } @@ -154,11 +259,13 @@ try { } $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeArchitecture='64'} $media = Initialize-OfficeMedia $options $mediaWorkspace - Assert-OfficeTest ((Get-Content -LiteralPath $media.Scrubber -Raw) -eq 'Inert scrubber fixture; never executed.') 'Get Help ZIP did not extract correctly with Tools loaded and a literal path.' - 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.Setup -in $script:mediaSignatures) 'Extracted 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 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.' } & { $script:staged = @(); $script:verified = @() @@ -178,10 +285,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 +302,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.' @@ -258,12 +376,97 @@ try { Assert-OfficeThrows { Get-OfficeOdtDownloadUrl 'blocked' } 'unique current ODT' Assert-OfficeThrows { Get-OfficeOdtDownloadUrl ($url + ' ' + $url.Replace('20326','20327')) } 'unique current ODT' Assert-OfficeThrows { Get-OfficeOdtDownloadUrl 'https://download.microsoft.com.evil.test/officedeploymenttool_1.exe' } 'unique current ODT' - Assert-OfficeScrubResult 0 '00: Successfully completed this scenario.' @() - Assert-OfficeScrubResult 0 '66: No matching version.' @() - Assert-OfficeThrows { Assert-OfficeScrubResult 0 '09: Failure to remove Office.' @() } 'removal failed' - Assert-OfficeThrows { Assert-OfficeScrubResult 0 'Starting scenario...' @() } 'no recognizable' - Assert-OfficeThrows { Assert-OfficeScrubResult 1 '00: Success.' @() } 'removal failed' - Assert-OfficeThrows { Assert-OfficeScrubResult 0 '68: No product.' @([pscustomobject]@{DisplayName='Office 2016'}) } 'Office remains' + & { + function Get-OfficeUninstallEntries { + [pscustomobject]@{DisplayName='Microsoft Office Professional Plus 2016'; WindowsInstaller=1} + [pscustomobject]@{DisplayName='Microsoft Office Home and Business 2021 - en-us'} + [pscustomobject]@{DisplayName='Microsoft Teams Meeting Add-in for Microsoft Office'; WindowsInstaller=1} + } + function Test-Path { param($LiteralPath,$ErrorAction) $script:c2rPresent } + function Get-ItemProperty { throw 'Click-to-Run inventory access denied' } + $script:c2rPresent=$false + $inventory = @(Get-OfficeSuiteInventory) + Assert-OfficeTest ($inventory.Count -eq 2 -and $inventory[0].WindowsInstaller -eq 1) 'Office inventory must preserve the MSI marker and exclude the Teams add-in.' + $script:c2rPresent=$true + Assert-OfficeThrows { Get-OfficeSuiteInventory } 'Click-to-Run inventory access denied' + } + & { + function Get-OfficeSuiteInventory { + $script:removalChecks++ + if ($script:removalMode -eq 'empty') { return } + [pscustomobject]@{DisplayName='Microsoft Office Professional Plus 2016'; WindowsInstaller=1} + if ($script:removalMode -eq 'msi-only') { return } + if ($script:removalStarted -and $script:removalMode -eq 'read-error') { throw 'Office inventory is unreadable' } + if (!$script:removalStarted -or $script:removalMode -eq 'remaining' -or ($script:removalMode -eq 'delayed' -and $script:removalChecks -le 3)) { + [pscustomobject]@{DisplayName='Microsoft Office Home and Business 2021 - en-us'} + } + } + function Invoke-OfficeProcess { + param($FilePath,$Arguments,$LogPrefix) + $script:removalCalls++; $script:removalStarted=$true + Assert-OfficeTest ($FilePath -eq $media.Setup -and $Arguments -eq ('/configure "' + $media.RemovalConfig + '"')) 'Removal must run only ODT with the staged removal configuration.' + Assert-OfficeTest ((Split-Path -Leaf $LogPrefix) -eq 'office-remove') 'Removal must retain diagnostic process logs.' + $script:removalCode + } + $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','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} } + if ($script:removalMode -eq 'remaining') { + Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'Office remains.*Office Home and Business 2021.*manual scrub' + 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' + } else { + $result = @(Remove-OfficeSuite $media $testRoot) + $expected = if ($script:removalMode -eq 'reboot') {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) 'Do not remove absent Click-to-Run Office, rerun failed removal, or launch a fallback scrubber.' + } + } + & { + function Get-OfficeSuiteInventory { + $script:restartChecks++ + if ($script:restartMode -eq 'read-error') { throw 'Removal inventory access denied' } + if ($script:restartMode -eq 'remaining' -or ($script:restartMode -eq 'delayed' -and $script:restartChecks -lt 3)) { + [pscustomobject]@{DisplayName='Old Office fixture'} + } + # MSI Office is intentionally left for RemoveMSI during replacement installation. + if ($script:restartMode -eq 'msi-only') { [pscustomobject]@{DisplayName='MSI Office fixture'; WindowsInstaller=1} } + } + function Get-OfficeMachineCompanionEntries { Get-OfficeSuiteInventory } + foreach ($stage in @('Office','Companions')) { + foreach ($behavior in @($true,$false)) { + foreach ($script:restartMode in @('gone','remaining','delayed','read-error')) { + $script:restartChecks=0 + $options = [pscustomobject]@{DeferReboot=$behavior} + if ($behavior -and $script:restartMode -eq 'read-error') { + Assert-OfficeThrows { Test-OfficeCanDeferRestart $options $stage } 'Removal inventory access denied' + } else { + $result = @(Test-OfficeCanDeferRestart $options $stage) + $expected = $behavior -and $script:restartMode -in @('gone','delayed') + Assert-OfficeTest ($result.Count -eq 1 -and $result[0] -eq $expected) "Incorrect restart decision: $stage / $behavior / $script:restartMode." + if (!$behavior) { Assert-OfficeTest ($script:restartChecks -eq 0) 'DeferReboot=false must return immediately after a restart request.' } + elseif ($script:restartMode -eq 'remaining') { Assert-OfficeTest ($script:restartChecks -eq ((Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts + 1)) 'Deferral must wait for removal registration, with a bounded deadline.' } + elseif ($script:restartMode -eq 'delayed') { Assert-OfficeTest ($script:restartChecks -eq 3) 'Deferral must tolerate delayed removal registration.' } + } + } + } + } + $script:restartMode='msi-only'; $script:restartChecks=0 + Assert-OfficeTest (Test-OfficeCanDeferRestart ([pscustomobject]@{DeferReboot=$true}) 'Office') 'Deferred MSI removal must not block Click-to-Run restart deferral.' + foreach ($value in @($null, 'false', 'true', 'invalid')) { + Assert-OfficeThrows { Test-OfficeCanDeferRestart ([pscustomobject]@{DeferReboot=$value}) 'Office' } 'must be a validated Boolean' + } + } Assert-OfficeTest (Test-OfficeCredentialTarget 'MicrosoftOffice16_Data:ADAL:example') 'Office ADAL credential should be cleared.' foreach ($target in @('WindowsLive:target', 'MicrosoftAccount:user', 'OneDrive:user', 'AzureAD:user', 'TERMSRV/server', 'MicrosoftOffice16_DataEvil')) { Assert-OfficeTest (!(Test-OfficeCredentialTarget $target)) "Unrelated credential matched: $target" } Assert-OfficeTest ('Microsoft.AAD.BrokerPlugin' -notin (Get-OfficeAppxNames)) 'Must preserve Windows work-account broker.' @@ -275,6 +478,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' @@ -297,7 +590,9 @@ try { } & { function Invoke-OfficeProcess { return $script:installCode } + function Get-OfficeSuiteInventory { } 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 +606,29 @@ 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.' + function Get-ItemProperty { $script:installed } + function Get-OfficeSuiteInventory { + $script:msiChecks++ + if ($script:msiMode -eq 'read-error') { throw 'MSI inventory access denied' } + if ($script:msiChecks -eq 1 -or $script:msiMode -eq 'remaining' -or ($script:msiMode -eq 'delayed' -and $script:msiChecks -lt 4)) { + [pscustomobject]@{DisplayName='Microsoft Office Professional Plus 2016'; WindowsInstaller=1} + } + } + foreach ($script:msiMode in @('removed','delayed','remaining','read-error')) { + $script:msiChecks=0 + if ($script:msiMode -eq 'remaining') { + Assert-OfficeThrows { Install-OfficeMedia $options $media $testRoot } 'MSI Office remains.*Office Professional Plus 2016.*new suite may already be installed.*manual scrub' + Assert-OfficeTest ($script:msiChecks -eq ((Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts + 2)) 'MSI removal must be verified with a bounded wait.' + } elseif ($script:msiMode -eq 'read-error') { + Assert-OfficeThrows { Install-OfficeMedia $options $media $testRoot } 'MSI inventory access denied' + } else { + Assert-OfficeTest ((Install-OfficeMedia $options $media $testRoot) -eq 3010) 'Verified MSI removal requires a restart even if ODT returns zero.' + if ($script:msiMode -eq 'delayed') { Assert-OfficeTest ($script:msiChecks -eq 4) 'MSI removal must allow registry propagation time.' } + } + } } & { $script:registered = @(); $script:started = @(); $script:removed = @() @@ -327,11 +645,122 @@ 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.' + } + + # Real temporary files for cache reuse/tampering; no installer or network may run. + & { + $cacheRoot = Join-Path $testRoot 'cache-tests'; $null = [IO.Directory]::CreateDirectory($cacheRoot) + $source = Join-Path $cacheRoot ('a' * 32); $null = [IO.Directory]::CreateDirectory($source) + # LiteralPath matters: the staged fixture intentionally contains brackets. + foreach ($file in Get-ChildItem -LiteralPath (Join-Path $testRoot 'media [literal]')) { Copy-Item -LiteralPath $file.FullName -Destination $source -Recurse } + $target = Join-Path $cacheRoot ('b' * 32); $null = [IO.Directory]::CreateDirectory($target) + $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeArchitecture='64'; COMPANY='New Company'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'} + $script:rejectCacheSignature = $false; $script:helperDownloads = 0 + function Get-CimInstance { } + function Assert-OfficeMicrosoftSignature { param($Path) if ($script:rejectCacheSignature) { throw 'Untrusted cache signature' }; Assert-OfficeTest (Test-Path -LiteralPath $Path) 'Cache signature target was missing.' } + function Save-OfficeDownload { param($Uri,$Path) if ([IO.Path]::GetFileName($Path) -ne 'Office-UserCleanup.ps1') { throw 'Unexpected network download on cache hit' }; $script:helperDownloads++; Set-Content -LiteralPath $Path -Value ('# ' + (Get-OfficeDeploymentDefinitions).HelperVersion) } + function Invoke-OfficeProcess { throw 'A cached deployment must not redownload Office.' } + $manifestPath = Join-Path $source 'media-cache.json' + $originalManifest = Get-Content -LiteralPath $manifestPath -Raw + $different = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5'; OfficeArchitecture='64'} + Assert-OfficeTest (!(Restore-OfficeMediaCache $different $target)) 'Teams selection mismatch reused the wrong cache.' + $different = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeArchitecture='64'; UpdateChannel='MonthlyEnterprise'} + Assert-OfficeTest (!(Restore-OfficeMediaCache $different $target)) 'Channel mismatch reused the wrong cache.' + $manifest = $originalManifest | ConvertFrom-Json; $manifest.CreatedUtc = [DateTime]::UtcNow.AddDays(-8).ToString('o') + $manifest | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $manifestPath + Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Expired cache was reused.' + Set-Content -LiteralPath $manifestPath -Value $originalManifest + $stream = Join-Path $source 'ODT\Office\Data\16.0.12345.67890\stream.x64.x-none.dat' + $originalBytes = [IO.File]::ReadAllBytes($stream); $changedBytes = $originalBytes.Clone(); $changedBytes[0] = $changedBytes[0] -bxor 1; [IO.File]::WriteAllBytes($stream, $changedBytes) + Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Same-size payload corruption passed hash verification.' + [IO.File]::WriteAllBytes($stream, $originalBytes) + $extra = Join-Path $source 'ODT\unexpected.dll'; Set-Content -LiteralPath $extra -Value 'unexpected dependency' + Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Unrecorded executable dependencies passed cache verification.' + Remove-OfficeManagedItem $cacheRoot $extra + function Get-CimInstance { [pscustomobject]@{CommandLine="setup.exe $source\install.xml"} } + Assert-OfficeThrows { Restore-OfficeMediaCache $options $target } 'previous Office deployment still has active processes' + Assert-OfficeTest (Test-Path -LiteralPath $stream) 'A live installer lost its cached media.' + function Get-CimInstance { } + $script:rejectCacheSignature = $true + Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Invalid Microsoft signature was reused.' + $script:rejectCacheSignature = $false + $media = Initialize-OfficeMedia $options $target + Assert-OfficeTest ($media.CachedMediaReused -and $media.Version -eq '16.0.12345.67890' -and $script:helperDownloads -eq 1) 'Deployment did not reuse the validated media and refresh the helper.' + Assert-OfficeTest (!(Test-Path -LiteralPath (Join-Path $source 'ODT')) -and (Test-Path -LiteralPath $media.Setup)) 'Cache transfer duplicated large files or lost setup.' + $config = [xml](Get-Content -LiteralPath $media.Config -Raw) + Assert-OfficeTest ($config.Configuration.AppSettings.Setup.Value -eq 'New Company' -and $config.Configuration.Add.SourcePath -eq (Join-Path $target 'ODT')) 'Reused media retained stale company/configuration paths.' + Assert-OfficeTest ((Get-Content -LiteralPath (Join-Path $target 'media-cache.json') -Raw | ConvertFrom-Json).CreatedUtc -eq ($originalManifest | ConvertFrom-Json).CreatedUtc) 'Reuse extended cache expiry.' + Assert-OfficeThrows { Remove-OfficeManagedItem $cacheRoot $testRoot } 'outside the Office deployment root' + Assert-OfficeThrows { Remove-OfficeManagedItem $cacheRoot $cacheRoot } 'outside the Office deployment root' + } + # Cleanup runs synchronously on success. Downloads are temporary; pending-user + # helpers have a separate durable folder and are never part of the media cache. + & { + $root = Join-Path $testRoot 'temporary-downloads'; $null = [IO.Directory]::CreateDirectory($root) + $workspace = Join-Path $root ('c' * 32); $null = [IO.Directory]::CreateDirectory($workspace) + foreach ($name in @('options.json', 'Office-UserCleanup.ps1', 'user-cleanup.lock', 'office-install.stdout.log', 'odt.exe')) { Set-Content -LiteralPath (Join-Path $workspace $name) -Value 'fixture' } + $null = [IO.Directory]::CreateDirectory((Join-Path $workspace 'ODT')) + Set-Content -LiteralPath (Join-Path $workspace 'ODT\payload') -Value 'fixture' + $userRoot = Join-Path $testRoot 'durable-user-helpers'; $null = [IO.Directory]::CreateDirectory($userRoot) + function New-OfficeWorkspace { + param($Root,$DeploymentId) + Assert-OfficeTest ($Root -eq (Join-Path $env:ProgramData 'EmberkomOfficeDeployment') -and $DeploymentId -eq ('c' * 32)) 'Pending-user helper must use a separate protected ProgramData workspace.' + $path = Join-Path $userRoot $DeploymentId; $null = [IO.Directory]::CreateDirectory($path) + Set-Content -LiteralPath (Join-Path $path 'user-cleanup.lock') -Value '' + $path + } + $media = [pscustomobject]@{Helper=(Join-Path $workspace 'Office-UserCleanup.ps1')} + $userWorkspace = New-OfficeUserWorkspace $media $workspace + Assert-OfficeTest ($media.Helper -eq (Join-Path $userWorkspace 'Office-UserCleanup.ps1') -and (Test-Path -LiteralPath $media.Helper)) 'User helper was not separated from cached installers.' + $script:cleanupTasks = $true; $script:cleanupProcess = $true + function Get-CimInstance { if ($script:cleanupProcess) { [pscustomobject]@{CommandLine="setup.exe $workspace\install.xml"} } } + function Get-ScheduledTask { if ($script:cleanupTasks) { [pscustomobject]@{TaskName="Emberkom-OfficeCleanup-$('c' * 32)-SID"; State='Ready'} } } + function Register-ScheduledTask { throw 'File cleanup must not register any task.' } + $warnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace + Assert-OfficeTest ($warnings.Count -and (Test-Path -LiteralPath (Join-Path $workspace 'ODT'))) 'Cleanup deleted files referenced by a surviving installer.' + $script:cleanupProcess = $false + $warnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace + Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath $workspace)) 'Successful deployment left its temporary workspace behind.' + Assert-OfficeTest (Test-Path -LiteralPath $media.Helper) 'Temporary cache cleanup deleted the pending-user helper.' + $script:cleanupTasks = $false + $warnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace + Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath $userWorkspace)) 'Completed user cleanup left its helper folder behind.' + # Older ProgramData stages lose only known downloads, never deferred-user files. + $legacy = Join-Path $userRoot ('d' * 32); $null = [IO.Directory]::CreateDirectory($legacy) + foreach ($name in @('options.json','odt.exe','Office-UserCleanup.ps1','user-cleanup.lock')) { Set-Content -LiteralPath (Join-Path $legacy $name) -Value 'fixture' } + $warnings = Complete-OfficeDeploymentFiles $workspace -PreviousRoot $userRoot + Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath (Join-Path $legacy 'odt.exe')) -and (Test-Path -LiteralPath (Join-Path $legacy 'Office-UserCleanup.ps1'))) 'Legacy download cleanup lost pending-user state or left old downloads.' + } + # The legacy uninstaller must delete both successful and partial downloads. + & { + $legacy = Read-OfficeAst 'Uninstall-MicrosoftOffice.ps1' + function End-Process { } + function Get-TempPath { $testRoot } + function Download-File { param($URL,$File) $script:legacyDownload=$File; Set-Content -LiteralPath $File -Value 'inert VBS'; if ($script:legacyMode -eq 'download') { throw 'synthetic download failure' }; $File } + function Start-Process { if ($script:legacyMode -eq 'launch') { throw 'synthetic launch failure' } } + foreach ($script:legacyMode in @('success', 'download', 'launch')) { + $failed=$false + try { $null = & ([scriptblock]::Create($legacy.Extent.Text)) 2>$null } catch { $failed=$true } + Assert-OfficeTest (!(Test-Path -LiteralPath $script:legacyDownload)) "Legacy uninstaller left its $script:legacyMode download behind." + Assert-OfficeTest ($failed -eq ($script:legacyMode -ne 'success')) 'Legacy cleanup swallowed the original failure.' + } } # Test orchestration with every machine mutation mocked. & { + function New-Object { + param($TypeName,$ArgumentList) + # Do not open the production mutex: a real SYSTEM deployment may be running. + if ($TypeName -eq 'Threading.Mutex') { return [Threading.Mutex]::new($false) } + throw "Unexpected object requested by orchestration fixture: $TypeName" + } function Assert-OfficeDeploymentHost { } + function Complete-OfficeDeploymentFiles { param($Workspace,$UserWorkspace,$PreviousRoot) $script:artifactCleanupRuns++; if ($script:mode -eq 'cleanup-warning') { return ,@('Synthetic file in use') }; return ,@() } + function New-OfficeUserWorkspace { param($Media,$Workspace) $Workspace } + function Register-ScheduledTask { throw 'Unexpected task registration in orchestration fixture.' } function New-OfficeWorkspace { $path = Join-Path $testRoot ([guid]::NewGuid().ToString('N')); $null = New-Item -ItemType Directory -Path $path; $path } function Start-Transcript { } function Stop-Transcript { } @@ -339,39 +768,63 @@ 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 { [pscustomobject]@{DisplayName='Synthetic Office'} } - function Initialize-OfficeMedia { $script:events += 'download'; if ($script:mode -eq 'download') { throw 'download failure' }; [pscustomobject]@{Version='16.0.1.2'} } + function Get-OfficeSuiteInventory { if ($script:mode -ne 'office-reboot' -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 -eq 'download') { 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 += 'scrub'; if ($script:mode -eq 'scrub') { throw 'scrub failure' } } + 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 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' }; if ($script:mode -eq 'pending') { return ,@('S-1-5-21-test') }; return ,@() } function Set-OfficeReinstallPhase { $script:events += 'phase'; if ($script:mode -eq 'phase') { throw 'user still holds cleanup lock' } } function Install-OfficeMedia { $script:events += 'install'; if ($script:mode -eq 'install') { throw 'install failure' }; return 0 } function Install-OfficeCompanionApps { param($Media,$Workspace,[bool]$InstallTeams) $script:teamsRequested=$InstallTeams; $script:events += 'install-companions'; if ($script:mode -eq 'install-companions') { throw 'companion install failure' }; [pscustomobject]@{ExitCode=$(if ($script:mode -eq 'companion-reboot') {3010} else {0}); Versions=@{NewOutlook='1'; OneDrive='1'}} } - $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'} - foreach ($script:mode in @('success','download','companions','scrub','identity','user','phase','install','install-companions','pending','reboot','companion-reboot')) { + $script:removalStillRegistered=$false + $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'; DeferReboot='false'} + foreach ($script:mode in @('success','download','companions','remove-office','identity','user','phase','install','install-companions','pending','reboot','office-reboot','companion-reboot')) { + $script:artifactCleanupRuns = 0 $script:events = @(); $errorResult = $null; $result = $null try { $result = Invoke-OfficeDeployment $options } catch { $errorResult = $_ } - if ($script:mode -in @('success','pending','reboot','companion-reboot')) { + if ($script:mode -in @('success','pending','reboot','office-reboot','companion-reboot')) { Assert-OfficeTest ($null -eq $errorResult) "Unexpected failure in $script:mode : $errorResult" - $code = switch ($script:mode) { 'success' {0}; 'pending' {2}; 'reboot' {3010}; 'companion-reboot' {3010} } + $code = switch ($script:mode) { 'success' {0}; 'pending' {2}; 'reboot' {3010}; 'office-reboot' {3010}; 'companion-reboot' {3010} } Assert-OfficeTest ($result.ExitCode -eq $code) "Wrong result code for $script:mode" } else { Assert-OfficeTest ($null -ne $errorResult) "Failure swallowed in $script:mode" } if ($script:mode -notin @('success','pending','install','install-companions','companion-reboot')) { Assert-OfficeTest ('install' -notin $script:events) "Install ran after $script:mode failure/reboot." } if ($script:mode -notin @('success','pending','install-companions','companion-reboot')) { Assert-OfficeTest ('install-companions' -notin $script:events) "Companion install ran after $script:mode failure/reboot." } - if ($script:mode -eq 'download') { Assert-OfficeTest ('companions' -notin $script:events -and 'scrub' -notin $script:events) 'Removal ran after download failed.' } - if ($script:mode -eq 'success') { Assert-OfficeTest (($script:events -join ',') -eq 'download,apps,companions,scrub,identity,user,phase,install,install-companions') 'Deployment order changed.' } + if ($script:mode -eq 'download') { Assert-OfficeTest ('companions' -notin $script:events -and 'remove-office' -notin $script:events) 'Removal ran after download failed.' } + Assert-OfficeTest ($script:artifactCleanupRuns -eq $(if ($script:mode -in @('success','pending','companion-reboot')) {1} else {0})) "Media cleanup ran before successful installation, or was skipped after success: $script:mode" + 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.' } } + $script:mode='cleanup-warning'; $script:events=@() + $result = @(Invoke-OfficeDeployment $options) + Assert-OfficeTest ($result.Count -eq 1 -and $result[0].ArtifactCleanupPending -and $result[0].ExitCode -eq 0 -and $result[0].OfficeDeploymentStatus -eq 'Installed') 'Artifact cleanup problems corrupted the receipt or failed a verified installation.' + foreach ($script:mode in @('reboot','office-reboot')) { + foreach ($script:removalStillRegistered in @($false,$true)) { + $script:events=@() + $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'} + $result = Invoke-OfficeDeployment $options + Assert-OfficeTest ($result.ExitCode -eq 3010 -and $result.RestartRequired -and $result.DeferReboot -is [bool] -and $result.DeferReboot) 'A deferred removal restart must survive later zero-exit installers in the final result.' + if ($script:removalStillRegistered) { + Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'RestartRequiredBeforeInstall' -and 'install' -notin $script:events -and 'install-companions' -notin $script:events) 'Incomplete removal must still stop before installation with DeferReboot=true.' + } else { + Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'Installed' -and 'install' -in $script:events -and 'install-companions' -in $script:events) 'Verified removal should complete installation without an intervening restart.' + } + } + } + $script:removalStillRegistered=$false $script:mode='success'; $script:events=@() $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'} $result = Invoke-OfficeDeployment $options Assert-OfficeTest (!$script:teamsRequested -and !$result.TeamsSelected) 'Deployment did not pass the no-Teams choice to companion installation/reporting.' + Assert-OfficeTest (!$result.RestartRequired -and $result.ExitCode -eq 0) 'A clean deployment without restart requests must not demand a restart.' foreach ($shutdown in @('Abort','Force')) { foreach ($validate in @($null, '', 'true')) { $script:events=@() $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeAppShutdown=$shutdown; ValidateBeforeChanges=$validate} $result = Invoke-OfficeDeployment $options Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'ValidationPassed' -and $result.ExitCode -eq 0 -and $result.ValidateBeforeChanges) 'Validation did not produce a distinct result.' + Assert-OfficeTest ($result.OfficeRemovalMethod -eq 'SilentODT' -and $result.DeferReboot -is [bool] -and $result.DeferReboot) 'Validation must identify the silent removal method and Boolean restart selection.' Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Validation reached app shutdown, removal, identities, user tasks, phase changes, or installation.' Assert-OfficeTest (!$result.TeamsSelected -and $result.ProfileCount -eq 1 -and $result.ExistingOffice[0] -eq 'Synthetic Office') 'Validation report lost the deployment plan.' } @@ -389,6 +842,9 @@ try { Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Failed validation reached mutations.' $options.ValidateBeforeChanges='false' Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'validated Boolean' + $options.ValidateBeforeChanges=$false; $options.DeferReboot='false'; $script:events=@() + Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'DeferReboot must be a validated Boolean' + Assert-OfficeTest ($script:events.Count -eq 0) 'Unparsed restart input must fail before any deployment action.' } # Exercise unchanged Run-Script with injected strings; all downloads return inert source. @@ -425,7 +881,7 @@ function Invoke-OfficeDeployment { if ($script:ProbeMode -eq 'failure') { throw 'Simulated deployment failure.' } if ($script:ProbeMode -eq 'missing') { return } $null = Write-Output 'Mock action diagnostic' - [pscustomobject]@{OfficeDeploymentStatus='Mocked'; ExitCode=$script:ProbeExitCode; ProductId=$Options.ProductId; Company=$Options.Company; Activation=$Options.OfficeActivation; ValidateBeforeChanges=$Options.ValidateBeforeChanges} + [pscustomobject]@{OfficeDeploymentStatus='Mocked'; ExitCode=$script:ProbeExitCode; ProductId=$Options.ProductId; Company=$Options.Company; Activation=$Options.OfficeActivation; ValidateBeforeChanges=$Options.ValidateBeforeChanges; DeferReboot=$Options.DeferReboot} } '@ $mockCore = $coreAst.Extent.Text.Remove($workload.Extent.StartOffset, $workload.Extent.EndOffset - $workload.Extent.StartOffset).Insert($workload.Extent.StartOffset, $mockWorkload) @@ -461,7 +917,7 @@ function New-Object { __LAUNCH__ '@ function ConvertTo-OfficeTestBase64 { param([string]$Text) [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($Text)) } - $probeValues = @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeActivation='SharedComputer'; ValidateBeforeChanges='false'; COMPANY='A & B '' " $() `company`'} + $probeValues = @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeActivation='SharedComputer'; ValidateBeforeChanges='false'; DeferReboot='false'; COMPANY='A & B '' " $() `company`'} $shimSource = Get-Content -LiteralPath (Join-Path $repo 'rmm\Install-MicrosoftOffice365.ps1') -Raw foreach ($case in @(@{Mode='success';Code=0;Validate='true'},@{Mode='success';Code=0;Validate=''},@{Mode='success';Code=0;Validate='false'},@{Mode='success';Code=2;Validate='false'},@{Mode='success';Code=3010;Validate='false'},@{Mode='failure';Code=1;Validate='false'},@{Mode='missing';Code=1;Validate='true'})) { $probeValues.ValidateBeforeChanges=$case.Validate @@ -478,6 +934,7 @@ __LAUNCH__ $receipt = $probeText.Substring($probeText.IndexOf('{')) | ConvertFrom-Json Assert-OfficeTest ($receipt.ProductId -eq 'O365ProPlusEEANoTeamsRetail' -and $receipt.Company -ceq $probeValues.COMPANY -and $receipt.Activation -eq 'SharedComputer') 'Shim lost injected strings before main workload.' Assert-OfficeTest ($receipt.ValidateBeforeChanges -eq ($case.Validate -ne 'false')) 'Shim lost the validation gate.' + Assert-OfficeTest ($receipt.DeferReboot -is [bool] -and !$receipt.DeferReboot) 'Shim/main entry lost or misparsed the injected false restart string.' $probeLog = Get-Content -LiteralPath (Join-Path $testRoot 'probe-management.log') -Raw Assert-OfficeTest ($probeLog -match 'Mock action diagnostic' -and $probeLog -match '"OfficeDeploymentStatus"' -and $probeText -notmatch 'Mock action diagnostic') 'Diagnostics or receipt did not reach the correct log/console destination.' Assert-OfficeTest ($probeLog -notmatch 'Validation only:|Diagnostic log:') 'Console-only output was unexpectedly logged.' @@ -488,13 +945,14 @@ __LAUNCH__ } } # Exercise the native-host command with the same network mock and an inert child workload. - $nativePayload = '$null = Write-Output "Native logging diagnostic"; [pscustomobject]@{Subscription=$OfficeSubscription; Company=$COMPANY; Activation=$OfficeActivation; ValidateBeforeChanges=(ConvertTo-RmmBoolean $ValidateBeforeChanges); LogFile=$Global:LogFile} | ConvertTo-Json -Compress; exit 2' + $nativePayload = '$null = Write-Output "Native logging diagnostic"; [pscustomobject]@{Subscription=$OfficeSubscription; Company=$COMPANY; Activation=$OfficeActivation; ValidateBeforeChanges=(ConvertTo-RmmBoolean $ValidateBeforeChanges); DeferReboot=(ConvertTo-RmmBoolean $DeferReboot); LogFile=$Global:LogFile} | ConvertTo-Json -Compress; exit 2' $probe = $probeTemplate.Replace('__TOOLS__', (ConvertTo-OfficeTestBase64 $mockToolsText)).Replace('__CORE__', (ConvertTo-OfficeTestBase64 $nativePayload)).Replace('__VALUES__', (ConvertTo-OfficeTestBase64 '{}')).Replace('__MODE__', 'success').Replace('__CODE__', '2').Replace('__LAUNCH__', (New-OfficeNativeCommand $probeValues)) $probePath = Join-Path $testRoot 'native-probe.ps1'; Set-Content -LiteralPath $probePath -Value $probe $probeOutput = & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $probePath Assert-OfficeTest ($LASTEXITCODE -eq 2) 'Native-host command lost the workload exit code.' $receipt = $probeOutput | ConvertFrom-Json Assert-OfficeTest ($receipt.Subscription -ceq $probeValues.OfficeSubscription -and $receipt.Company -ceq $probeValues.COMPANY -and $receipt.Activation -eq 'SharedComputer') 'Native-host command changed injected strings.' + Assert-OfficeTest ($receipt.DeferReboot -is [bool] -and !$receipt.DeferReboot) 'Native-host command lost the false restart selection.' Assert-OfficeTest ($receipt.ValidateBeforeChanges -and $receipt.LogFile -eq $Global:LogFile -and (Get-Content -LiteralPath $Global:LogFile -Raw) -match 'Native logging diagnostic') 'Native-host command must reload Tools and preserve validation and the parent log.' # Simulate Syncro's 32-bit Windows PowerShell launching the native 64-bit 5.1 host. # Only the relaunch payload is replaced; host selection and process exit handling are real.