#Requires -Version 5.1 # Offline only: load function definitions via AST; never execute either script's entry point. $ErrorActionPreference = 'Stop' if ($PSVersionTable.PSEdition -ne 'Desktop' -or $PSVersionTable.PSVersion.Major -ne 5 -or $PSVersionTable.PSVersion.Minor -ne 1) { throw 'Run these checks with Windows PowerShell 5.1 (powershell.exe).' } $repo = Split-Path -Parent $PSScriptRoot $testRoot = Join-Path $env:TEMP ('OfficeDeploymentTests-' + [guid]::NewGuid().ToString('N')) $null = New-Item -ItemType Directory -Path $testRoot $script:assertions = 0 function Assert-OfficeTest { param([bool]$Condition, [string]$Message) $script:assertions++; if (!$Condition) { throw $Message } } function Assert-OfficeThrows { param([scriptblock]$Action, [string]$Pattern) $caught = $null try { & $Action | Out-Null } catch { $caught = $_ } Assert-OfficeTest ($null -ne $caught -and $caught.Exception.Message -match $Pattern) "Expected error '$Pattern', got '$caught'." } function Read-OfficeAst { param([string]$RelativePath) $tokens = $null; $errors = $null $ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $repo $RelativePath), [ref]$tokens, [ref]$errors) if ($errors.Count) { throw ($errors | Out-String) } return $ast } try { # Use the real boolean/logging helpers and archive override, without machine initialization. $toolsAst = Read-OfficeAst 'Tools.ps1' $toolHelpers = @($toolsAst.FindAll({ param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -in @('ConvertTo-RmmBoolean', 'Write-Output', 'Write-Error', 'Expand-Archive') }, $false)) foreach ($definition in $toolHelpers) { . ([scriptblock]::Create($definition.Extent.Text)) } $Global:LogFile = Join-Path $testRoot 'management.log' $coreAst = Read-OfficeAst 'Install-MicrosoftOffice365.ps1' $helperAst = Read-OfficeAst 'resources/office/Office-UserCleanup.ps1' $callerAst = Read-OfficeAst 'rmm/Install-MicrosoftOffice365.ps1' foreach ($ast in @($coreAst, $helperAst)) { foreach ($definition in $ast.FindAll({ param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] }, $false)) { . ([scriptblock]::Create($definition.Extent.Text)) } } # Exercise the real bounded retry loops without delaying offline tests. function Start-Sleep { param([int]$Seconds) $script:testSleeps += $Seconds } function Get-FileHash { throw 'Office deployment must not scan file checksums.' } $diskSpaceCheck = ${function:Assert-OfficeDiskSpace} # Staging/orchestration fixtures must not depend on this test computer's free space. function Assert-OfficeDiskSpace { param($Workspace,[switch]$DownloadingMedia) } $script:testSleeps = @() & { function Get-CimInstance { param($ClassName,$Filter) Assert-OfficeTest ($ClassName -eq 'Win32_LogicalDisk') 'Disk checks must use read-only logical-disk inventory.' $script:diskQueries += $Filter if ($script:diskReadFails) { throw 'Synthetic disk inventory failure' } if ($Filter -match "DeviceID='([^']+)'") { [pscustomobject]@{FreeSpace=$script:freeBytes[$Matches[1]]} } } $script:diskReadFails=$false; $script:diskQueries=@() $script:freeBytes=@{'C:'=16GB; 'D:'=6GB; 'E:'=10GB} $output = @(& $diskSpaceCheck -Workspace 'C:\Temp\Office' -InstallPaths @('C:\Windows','C:\Program Files') -DownloadingMedia) Assert-OfficeTest ($output.Count -eq 0 -and $script:diskQueries.Count -eq 1) 'A shared staging/install volume must combine reserves once without leaking log messages.' $script:freeBytes['C:']=16GB-1 Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'C:\Temp\Office' -InstallPaths @('C:\Windows') -DownloadingMedia } 'Insufficient disk space.*before downloading media.*16 GB.*Existing apps have not been removed' $script:freeBytes['C:']=10GB $null = & $diskSpaceCheck -Workspace 'C:\Temp\Office' -InstallPaths @('C:\Windows') $script:freeBytes['C:']=1701MB Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'C:\Temp\Office' -InstallPaths @('C:\Windows') } 'Insufficient disk space.*after staging, before removal' $script:freeBytes['C:']=10GB; $script:diskQueries=@() $null = & $diskSpaceCheck -Workspace 'D:\Temp\Office' -InstallPaths @('C:\Windows','E:\Program Files') -DownloadingMedia Assert-OfficeTest ($script:diskQueries.Count -eq 3) 'Separate staging, Windows, and application drives must each be checked.' $script:freeBytes['D:']=5GB Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'D:\Temp\Office' -InstallPaths @('C:\Windows') -DownloadingMedia } 'Insufficient disk space on D:.*6 GB' $script:freeBytes['C:']=$null Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'D:\Temp\Office' -InstallPaths @('C:\Windows') } 'Could not determine free space' $script:diskReadFails=$true Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'D:\Temp\Office' -InstallPaths @('C:\Windows') } 'Synthetic disk inventory failure' } & { $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 Write-OfficeSetupDiagnostics { param($SinceUtc) $script:diagnosticCalls++ Assert-OfficeTest ($SinceUtc -is [DateTime]) 'ODT diagnostics must use the actual process start time.' if ($script:diagnosticFails) { throw 'Synthetic locked diagnostic log' } } 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.' } foreach ($script:diagnosticFails in @($false, $true)) { $script:processExit=17004; $script:diagnosticCalls=0 $output = @(Invoke-OfficeProcess (Join-Path $testRoot 'setup.exe') '/configure inert.xml' (Join-Path $testRoot 'odt-failed')) Assert-OfficeTest ($output.Count -eq 1 -and $output[0] -eq 17004 -and $script:diagnosticCalls -eq 1) 'ODT native diagnostic collection must retain the original exit code and not pollute output, even when collection fails.' } $script:diagnosticFails=$false foreach ($script:processExit in @(0,3010)) { $script:diagnosticCalls=0 $null = Invoke-OfficeProcess (Join-Path $testRoot 'setup.exe') '/configure inert.xml' (Join-Path $testRoot 'odt-success') Assert-OfficeTest ($script:diagnosticCalls -eq 0) 'Successful ODT operations must not search unrelated native logs.' } } & { $nativeRoot = Join-Path $testRoot 'native-logs'; $null = [IO.Directory]::CreateDirectory($nativeRoot) $since = [DateTime]::UtcNow.AddMinutes(-1) $recent = Join-Path $nativeRoot ($env:COMPUTERNAME + '-20261022-test.log') [IO.File]::WriteAllLines($recent, @('Normal setup entry', 'Click-To-Run Error {"ErrorCode":12345,"ErrorMessage":"Synthetic setup reason"}')) $old = Join-Path $nativeRoot 'Office-old.log'; [IO.File]::WriteAllText($old, 'Error Old unrelated failure'); [IO.File]::SetLastWriteTimeUtc($old, $since.AddHours(-1)) $unrelated = Join-Path $nativeRoot 'OtherApplication.log'; [IO.File]::WriteAllText($unrelated, 'Error Unrelated app failure') $empty = Join-Path $nativeRoot 'Office-empty.log'; [IO.File]::WriteAllText($empty, '') $nested = Join-Path $nativeRoot 'nested'; $null = [IO.Directory]::CreateDirectory($nested) [IO.File]::WriteAllText((Join-Path $nested 'Office-nested.log'), 'Error Nested unrelated failure') $output = @(Write-OfficeSetupDiagnostics -SinceUtc $since -SearchRoots @($nativeRoot,$nativeRoot)) Assert-OfficeTest ($output.Count -eq 0) 'Native diagnostics must write through Tools logging without leaking return values.' $log = Get-Content -LiteralPath $Global:LogFile -Raw Assert-OfficeTest ($log -match 'Synthetic setup reason' -and $log.Contains($recent)) 'The management log must include the native filename and actual error detail.' Assert-OfficeTest (([regex]::Matches($log, 'Native Office detail:.*Synthetic setup reason')).Count -eq 1) 'Duplicate search roots must not duplicate diagnostics.' Assert-OfficeTest ($log -notmatch 'Old unrelated failure|Unrelated app failure|Nested unrelated failure|Office-empty.log') 'Diagnostics must exclude old, unrelated, empty, and nested logs.' Assert-OfficeTest ((Get-Content -LiteralPath $recent -Raw) -match 'Normal setup entry') 'Collecting native diagnostics must not modify the original log.' [IO.File]::WriteAllLines($recent, @(1..30 | ForEach-Object { "Error Bounded native detail $_" })) $null = Write-OfficeSetupDiagnostics -SinceUtc $since -SearchRoots @($nativeRoot) $log = Get-Content -LiteralPath $Global:LogFile -Raw Assert-OfficeTest (([regex]::Matches($log, 'Native Office detail: Error Bounded native detail')).Count -eq (Get-OfficeDeploymentDefinitions).SetupDiagnosticErrorLines) 'Native error excerpts must be bounded.' $null = Write-OfficeSetupDiagnostics -SinceUtc ([DateTime]::UtcNow.AddMinutes(1)) -SearchRoots @($nativeRoot) Assert-OfficeTest ((Get-Content -LiteralPath $Global:LogFile -Raw) -match 'No recent nonempty native Office logs found') 'Missing native logs must be reported without inventing a diagnosis.' function Get-Content { throw 'Synthetic native log read failure' } Assert-OfficeTest (@(Write-OfficeSetupDiagnostics -SinceUtc $since -SearchRoots @($nativeRoot)).Count -eq 0) 'A locked native log must not throw or alter the installer result.' } & { 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 $output = @(Save-OfficeDownload 'https://fixture.invalid/' (Join-Path $testRoot 'download') 2>&1) Assert-OfficeTest ($script:downloadCalls -eq 2 -and (Get-Content -LiteralPath (Join-Path $testRoot 'download') -Raw) -eq 'downloaded fixture') 'A transient download error should recover.' Assert-OfficeTest ($output.Count -eq 0) 'A recovered download must not emit success-stream diagnostics or Syncro errors.' $log = Get-Content -LiteralPath $Global:LogFile -Raw Assert-OfficeTest ($log -match 'Download attempt 1 of 3 failed for https://fixture.invalid/' -and $log -match 'Temporary network failure Retrying in 3 seconds' -and $log -match 'Download recovered on attempt 2: https://fixture.invalid/') 'Retry details and recovery must remain in the Tools diagnostic log.' $script:downloadCalls=0; $script:downloadRecovers=$false Assert-OfficeThrows { Save-OfficeDownload 'https://fixture.invalid/' (Join-Path $testRoot 'download') } 'Download failed after 3 attempts: https://fixture.invalid/.*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." } } } } & { # Personal Teams has a different process name from both classic and current Teams. # Exercise detection and both shutdown choices without touching real processes. function Get-Process { param($Name,$ErrorAction) foreach ($candidate in @('Teams','msteams','ms-teams','unrelated')) { if ($candidate -in $Name) { [pscustomobject]@{ProcessName=$candidate; Id=123; HasExited=$false} } } } function Stop-Process { param($InputObject,[switch]$Force,$ErrorAction) $script:stoppedTeams += $InputObject.ProcessName } $script:stoppedTeams=@() $running = @(Get-OfficeRunningApps) Assert-OfficeTest ($running.Count -eq 3 -and 'msteams' -in $running.ProcessName -and 'unrelated' -notin $running.ProcessName) 'Running-app detection must include personal Teams without broad process matching.' Assert-OfficeThrows { Stop-OfficeDeploymentApps ([pscustomobject]@{OfficeAppShutdown='Abort'}) } 'Apps are running:.*msteams' Assert-OfficeTest ($script:stoppedTeams.Count -eq 0) 'Abort must not close any Teams client.' Stop-OfficeDeploymentApps ([pscustomobject]@{OfficeAppShutdown='Force'}) Assert-OfficeTest ($script:stoppedTeams.Count -eq 3 -and 'msteams' -in $script:stoppedTeams) 'Force must close the older personal Teams client along with classic/current Teams.' } & { 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'." } foreach ($value in @('false', ' FALSE ', '$false', '0', 'no')) { $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; ValidateBeforeChanges=$value} Assert-OfficeTest ($options.ValidateBeforeChanges -is [bool] -and !$options.ValidateBeforeChanges) "Explicit opt-out '$value' was ignored." } Assert-OfficeTest ((Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'}).ValidateBeforeChanges) 'Missing validation input enabled changes.' Assert-OfficeThrows { Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; ValidateBeforeChanges='maybe'} } 'Invalid \$ValidateBeforeChanges' $expected = @{ 'Microsoft 365 Business Standard' = 'O365BusinessRetail' 'Microsoft 365 Business Premium' = 'O365BusinessRetail' 'Microsoft 365 Apps for business' = 'O365BusinessEEANoTeamsRetail' 'Microsoft 365 Apps for enterprise' = 'O365ProPlusEEANoTeamsRetail' 'Microsoft/Office 365 E3/E5' = 'O365ProPlusRetail' 'Microsoft 365 E3' = 'O365ProPlusRetail' 'Microsoft 365 E5' = 'O365ProPlusRetail' 'Office 365 E3' = 'O365ProPlusRetail' 'Office 365 E5' = 'O365ProPlusRetail' } foreach ($plan in @('Microsoft/Office 365 E3/E5', 'Microsoft/Office 365 E3/E5 (no Teams)')) { $options = Get-OfficeDeploymentOptions @{OfficeSubscription=$plan; OfficeActivation='SharedComputer'} Assert-OfficeTest ($options.OfficeSubscription -eq $plan -and $options.OfficeActivation -eq 'SharedComputer') 'Combined enterprise selection lost shared activation eligibility.' } foreach ($plan in @('Microsoft 365 E3','Microsoft 365 E5','Office 365 E3','Office 365 E5')) { $options = Get-OfficeDeploymentOptions @{OfficeSubscription=$plan} Assert-OfficeTest ($options.OfficeSubscription -eq 'Microsoft/Office 365 E3/E5') 'Legacy enterprise selection was not normalized.' $options = Get-OfficeDeploymentOptions @{OfficeSubscription="$plan (no Teams)"} Assert-OfficeTest ($options.OfficeSubscription -eq 'Microsoft/Office 365 E3/E5 (no Teams)') 'Legacy no-Teams selection was not normalized.' } $noCompany = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5'; COMPANY=' None '} Assert-OfficeTest ($noCompany.Company -eq '') 'Nonempty Syncro sentinel must omit company metadata.' foreach ($plan in @($expected.Keys)) { $options = Get-OfficeDeploymentOptions @{ OfficeSubscription = $plan } Assert-OfficeTest ($options.ProductId -eq $expected[$plan]) "Incorrect product for $plan" Assert-OfficeTest ($options.InstallTeams -eq ($plan -notlike '*Apps for*')) "Incorrect Teams selection for $plan" if ($plan -notlike '*Apps for*') { $withoutTeams = Get-OfficeDeploymentOptions @{ OfficeSubscription = "$plan (no Teams)" } $product = if ($plan -like '*Business*') { 'O365BusinessEEANoTeamsRetail' } else { 'O365ProPlusEEANoTeamsRetail' } Assert-OfficeTest ($withoutTeams.ProductId -eq $product) "Incorrect no-Teams product for $plan" Assert-OfficeTest (!$withoutTeams.InstallTeams) "Teams was selected for $plan (no Teams)" } } foreach ($plan in @('', 'Select a subscription', 'Microsoft 365 Business Basic', 'Office 365 E1', 'Microsoft 365 F3', '')) { Assert-OfficeThrows { Get-OfficeDeploymentOptions @{OfficeSubscription = $plan} } 'supported OfficeSubscription' } Assert-OfficeThrows { Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Standard'; OfficeActivation='SharedComputer'} } 'requires Business Premium' Assert-OfficeThrows { Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Apps for business'; OfficeActivation='SharedComputer'} } 'requires Business Premium' foreach ($plan in @('Microsoft 365 Business Premium', 'Microsoft 365 Business Premium (no Teams)', 'Microsoft 365 Apps for enterprise')) { $null = Get-OfficeDeploymentOptions @{OfficeSubscription=$plan; OfficeActivation='SharedComputer'} } foreach ($name in @('OfficeArchitecture', 'UpdateChannel', 'OfficeActivation', 'OfficeAppShutdown')) { $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') 'An explicitly selected Windows 10 build must be retained.' $latestXml = New-OfficeConfiguration $options 'C:\Office' Assert-OfficeTest (!$latestXml.Configuration.Add.HasAttribute('Version')) 'Ordinary deployments must let ODT select the latest version.' Assert-OfficeTest (!$roundTrip.Configuration.Updates.HasAttribute('TargetVersion') -and $roundTrip.Configuration.Updates.Enabled -eq 'TRUE') 'Installation selection must not freeze future Office updates.' Assert-OfficeTest ((Get-OfficeFeatureRelease -Build 19045 -ProductType 1) -eq '2608') 'Windows 10 must select feature release 2608.' Assert-OfficeTest ((Get-OfficeFeatureRelease -Build 22631 -ProductType 1) -eq '') 'Windows 11 must remain unpinned.' Assert-OfficeTest ((Get-OfficeFeatureRelease -Build 20348 -ProductType 3) -eq '') 'Windows Server must not be mistaken for Windows 10.' $releaseHistory = @' Version 2608 (Build 20326.20158) Version 2608 (Build 20326.20144) Version 2608 (Build 20326.20232) Version 2608 (Build 20326.20230) Version 2610 (Build 20527.20088) Version 2608 (Build 20326.99999) '@ foreach ($channel in @('Current','MonthlyEnterprise','SemiAnnual')) { $expectedBuild = @{Current='16.0.20326.20158'; MonthlyEnterprise='16.0.20326.20232'; SemiAnnual='16.0.20326.20230'}[$channel] Assert-OfficeTest ((Get-OfficeBuildFromHistory $releaseHistory $channel '2608') -eq $expectedBuild) "Wrong Windows 10 build selected for $channel." } $numericHistory = 'Version 2608 (Build 20326.9)Version 2608 (Build 20326.10)' Assert-OfficeTest ((Get-OfficeBuildFromHistory $numericHistory Current '2608') -eq '16.0.20326.10') 'Build sorting must be numeric and tolerate HTML formatting.' Assert-OfficeThrows { Get-OfficeBuildFromHistory 'Changed Microsoft page' Current '2608' } 'did not identify.*Existing Office has not been removed' Assert-OfficeThrows { Get-OfficeBuildFromHistory $releaseHistory Invalid '2608' } 'Invalid.*selection' foreach ($app in @('OneDrive','Groove','Teams','OutlookForWindows')) { Assert-OfficeTest ($app -in $roundTrip.Configuration.Add.Product.ExcludeApp.ID) "ODT must leave $app to the explicit companion installation stage." } Assert-OfficeCompanionPlatform -Build 22631 -ProductType 1 -Revision 0 -EditionId Professional Assert-OfficeCompanionPlatform -Build 20348 -ProductType 3 -Revision 2402 -EditionId ServerStandard Assert-OfficeThrows { Assert-OfficeCompanionPlatform -Build 18363 -ProductType 1 } 'build 19041' 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 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) $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, [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 ($Uri -eq (Get-OfficeDeploymentDefinitions).OfficeReleaseHistory) { Assert-OfficeTest ($Uri -eq (Get-OfficeDeploymentDefinitions).OfficeReleaseHistory) 'Windows 10 release lookup must use Microsoft history.' [IO.File]::WriteAllText($Path, $script:mediaHistory) } elseif ([IO.Path]::GetFileName($Path) -eq 'Office-UserCleanup.ps1') { [IO.File]::WriteAllText($Path, '# ' + (Get-OfficeDeploymentDefinitions).HelperVersion) } else { [IO.File]::WriteAllText($Path, 'Inert installer fixture; never executed.') } } function Assert-OfficeMicrosoftSignature { param([string]$Path) if (!(Test-Path -LiteralPath $Path -PathType Leaf)) { throw "Missing staged signature target: $Path" } $script:mediaSignatures += $Path } function Invoke-OfficeProcess { param([string]$FilePath, [string]$Arguments, [string]$LogPrefix) $script:mediaProcesses += [IO.Path]::GetFileName($FilePath) 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 } $downloadXml = [xml](Get-Content -LiteralPath (Join-Path $mediaWorkspace 'install.xml') -Raw) Assert-OfficeTest ($downloadXml.Configuration.Add.GetAttribute('Version') -eq $options.TargetOfficeVersion) 'The OS-specific build must be selected before downloading.' $payload = Join-Path $mediaWorkspace ('ODT\Office\Data\' + $script:mediaPayloadVersion) $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.') } } else { throw "Unexpected executable requested during staging: $FilePath $Arguments" } return 0 } $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeArchitecture='64'} $script:mediaPayloadVersion = '16.0.12345.67890' $media = Initialize-OfficeMedia $options $mediaWorkspace 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.HasAttribute('Version')) 'Staging must not pin ordinary installations to the downloaded build.' 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')) 'Ordinary media staging must not download the conditional scrubber.' foreach ($mode in @('win10', 'incompatible-download', 'history-unavailable')) { $mediaWorkspace = Join-Path $testRoot $mode; $null = [IO.Directory]::CreateDirectory($mediaWorkspace) $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Standard'; OfficeArchitecture='64'} $options.OfficeFeatureRelease = Get-OfficeFeatureRelease -Build 19045 -ProductType 1 $script:mediaProcesses = @(); $script:mediaDownloadCalls = 0 $script:mediaHistory = $releaseHistory $script:mediaPayloadVersion = '16.0.20326.20158' if ($mode -eq 'history-unavailable') { $script:mediaHistory = 'No eligible build' Assert-OfficeThrows { Initialize-OfficeMedia $options $mediaWorkspace } 'did not identify' Assert-OfficeTest (!$script:mediaProcesses.Count) 'Missing Windows 10 release data must stop before launching installers.' } elseif ($mode -eq 'incompatible-download') { $script:mediaPayloadVersion = '16.0.20527.20088' Assert-OfficeThrows { Initialize-OfficeMedia $options $mediaWorkspace } 'Downloaded Office build does not match the Windows 10 target' } else { $media = Initialize-OfficeMedia $options $mediaWorkspace Assert-OfficeTest ($media.Version -eq '16.0.20326.20158' -and $options.TargetOfficeVersion -eq $media.Version) 'Windows 10 must stage its compatible build.' Assert-OfficeTest (([xml](Get-Content -LiteralPath $media.Config -Raw)).Configuration.Add.Version -eq $media.Version) 'Windows 10 installation must retain the compatible target.' } } $mediaWorkspace = Join-Path $testRoot 'low-space-before-download'; $null = [IO.Directory]::CreateDirectory($mediaWorkspace) $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Standard'; OfficeArchitecture='64'} $script:mediaProcesses=@() function Assert-OfficeDiskSpace { param($Workspace,[switch]$DownloadingMedia) Assert-OfficeTest $DownloadingMedia.IsPresent 'A fresh download must include staging space.'; throw 'Synthetic insufficient download space' } Assert-OfficeThrows { Initialize-OfficeMedia $options $mediaWorkspace } 'Synthetic insufficient download space' Assert-OfficeTest (!$script:mediaProcesses.Count -and !(Test-Path -LiteralPath (Join-Path $mediaWorkspace 'odt.exe'))) 'Low space must stop before downloading or launching ODT.' } & { $script:staged = @(); $script:verified = @() function Save-OfficeDownload { param($Uri,$Path) $script:staged += $Path } function Assert-OfficeMicrosoftSignature { param($Path) $script:verified += $Path } $media = Initialize-OfficeCompanionMedia $testRoot -InstallTeams $true Assert-OfficeTest ($media.Count -eq 4 -and $script:staged.Count -eq 4 -and ($script:staged -join ',') -eq ($script:verified -join ',')) 'Every companion installer must be staged and signed before removal.' foreach ($plan in @('Microsoft 365 Business Standard (no Teams)', 'Microsoft 365 Business Premium (no Teams)', 'Microsoft/Office 365 E3/E5 (no Teams)', 'Microsoft 365 Apps for business', 'Microsoft 365 Apps for enterprise', 'Office 365 E3 (no Teams)')) { $options = Get-OfficeDeploymentOptions @{OfficeSubscription=$plan} $script:staged = @(); $script:verified = @() $media = Initialize-OfficeCompanionMedia $testRoot -InstallTeams $options.InstallTeams Assert-OfficeTest ($media.Count -eq 3 -and !$media.ContainsKey('Teams') -and !($script:staged -match 'teamsbootstrapper')) "Teams was downloaded for $plan" $configuration = New-OfficeConfiguration $options $testRoot Assert-OfficeTest ('Teams' -in $configuration.Configuration.Add.Product.ExcludeApp.ID) "ODT could install Teams for $plan" } function Assert-OfficeMicrosoftSignature { throw 'Untrusted companion installer.' } Assert-OfficeThrows { Initialize-OfficeCompanionMedia $testRoot } 'Untrusted companion' } & { 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 } return 0 } 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 -eq 'personal-Teams-only') { [pscustomobject]@{DisplayName='MicrosoftTeams'; PackageName='MicrosoftTeams_1.0.0.0_neutral_~_8wekyb3d8bbwe'; Version='1.0.0.0'} } elseif ($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 -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','delayed-success','reboot','fail-WebView2','fail-OneDrive','fail-Teams','fail-NewOutlook','missing-OneDrive','missing-Teams','missing-NewOutlook','personal-Teams-only')) { $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','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.' Assert-OfficeTest (($script:appCalls -join '|') -eq 'WebView2 /silent /install|OneDrive /allusers /silent|Teams -p|NewOutlook --provision true --quiet --start-') 'Companion installers must run silently and for all users.' } else { Assert-OfficeTest ($null -ne $failure) "Companion failure was swallowed: $script:appMode" if ($script:appMode -eq 'personal-Teams-only') { Assert-OfficeTest ($failure.Exception.Message -match 'Teams setup returned success but the app was not provisioned') 'Legacy personal MicrosoftTeams must not satisfy MSTeams verification.' } if ($script:appMode -notlike '*NewOutlook') { Assert-OfficeTest (!($script:appCalls -match '^NewOutlook ')) 'Install continued after a companion failure.' } } } $script:appMode='success'; $script:webViewPresent=$true; $script:appCalls=@() $null = Install-OfficeCompanionApps $media $testRoot -InstallTeams $true Assert-OfficeTest (!($script:appCalls -match '^WebView2 ')) 'Existing machine WebView2 runtime was unnecessarily installed.' foreach ($plan in @('Microsoft 365 Business Standard (no Teams)', 'Microsoft 365 Business Premium (no Teams)', 'Microsoft/Office 365 E3/E5 (no Teams)', 'Microsoft 365 Apps for business', 'Microsoft 365 Apps for enterprise', 'Office 365 E5 (no Teams)')) { $options = Get-OfficeDeploymentOptions @{OfficeSubscription=$plan} $script:appMode='missing-Teams'; $script:webViewPresent=$true; $script:appCalls=@() # Even if Teams media is present, the license selection must prevent its use. $result = Install-OfficeCompanionApps $media $testRoot -InstallTeams $options.InstallTeams Assert-OfficeTest (($script:appCalls -join '|') -eq 'OneDrive /allusers /silent|NewOutlook --provision true --quiet --start-') "Teams was installed for $plan" Assert-OfficeTest ($result.ExitCode -eq 0 -and !$result.Versions.PSObject.Properties['Teams']) "Teams verification was required or reported for $plan" } } & { $cleanupWorkspace = Join-Path $testRoot 'cleanup-lock'; $null = New-Item -ItemType Directory -Path $cleanupWorkspace $null = New-Item -ItemType File -Path (Join-Path $cleanupWorkspace 'user-cleanup.lock') $script:preserved = @(); $script:credentialRuns = 0 function Clear-OfficeUserCredentials { $script:credentialRuns++ $otherHandle = $null try { $otherHandle = [IO.File]::Open((Join-Path $cleanupWorkspace 'user-cleanup.lock'), 'Open', 'Read', 'None') } catch [IO.IOException] { } try { Assert-OfficeTest ($null -eq $otherHandle) 'Cleanup did not hold an exclusive lock.' } finally { if ($otherHandle) { $otherHandle.Dispose() } } } function Remove-OfficeUserCompanions { param([switch]$PreserveReinstalledApps) $script:preserved += [bool]$PreserveReinstalledApps } Invoke-OfficeUserCleanup $cleanupWorkspace Set-OfficeReinstallPhase $cleanupWorkspace Invoke-OfficeUserCleanup $cleanupWorkspace Assert-OfficeTest ($script:credentialRuns -eq 2 -and !$script:preserved[0] -and $script:preserved[1]) 'Deferred cleanup can uninstall freshly installed companion apps.' } & { $script:legacyCleaned = $false function Remove-OfficeUserLegacyTeams { $script:legacyCleaned = $true } function Test-Path { throw 'Deferred cleanup must not inspect/remove the new OneDrive or Teams add-in.' } Remove-OfficeUserCompanions -PreserveReinstalledApps Assert-OfficeTest $script:legacyCleaned 'Deferred cleanup must still remove classic Teams.' } # Launch an inert executable through the same 5.1 Start-Process path used by Microsoft installers. $argumentProbe = Join-Path $testRoot 'OfficeArgumentProbe.exe' Add-Type -TypeDefinition 'using System; public static class OfficeArgumentProbe { public static int Main(string[] args) { Console.Write(String.Join("|", args)); return 0; } }' -OutputAssembly $argumentProbe -OutputType ConsoleApplication foreach ($arguments in @('-p', '--provision true --quiet --start-', '/allusers /silent', '/silent /install')) { $prefix = Join-Path $testRoot 'argument-probe' $code = Invoke-OfficeProcess $argumentProbe $arguments $prefix $actual = Get-Content -LiteralPath "$prefix.stdout.log" -Raw Assert-OfficeTest ($code -eq 0 -and $actual -ceq ($arguments.Split(' ') -join '|')) 'Windows PowerShell 5.1 changed native installer arguments.' } $url = 'https://download.microsoft.com/download/example/officedeploymenttool_20326-20112.exe' Assert-OfficeTest ((Get-OfficeOdtDownloadUrl "Download $url") -eq $url) 'Repeated valid link should resolve.' Assert-OfficeTest ((Get-OfficeOdtDownloadUrl $url.Replace('/', '\/')) -eq $url) 'JSON escaped download link should resolve.' 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' & { 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 -in @('empty','orphan')) { 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 -in @('remaining','corrupt') -or ($script:removalMode -eq 'delayed' -and $script:removalChecks -le 3)) { [pscustomobject]@{DisplayName='Microsoft Office Home and Business 2021 - en-us'} } } function Get-OfficeClickToRunState { [pscustomobject]@{Present=($script:removalMode -eq 'orphan');SourceReferences=@();WorkingConfiguration=@($(if ($script:removalMode -eq 'stale') {'old-guid'}))} } function Get-OfficeRemovalCorruptionEvidence { if ($script:removalMode -in @('corrupt','corrupt-gone')) { [pscustomobject]@{Path='fixture.log';Detail='REMOVEINSTALLATION InvalidDirectory'} } } function Get-CimInstance { @() } function Invoke-OfficeScrubRecovery { param($Media,$Workspace,$Reason) $script:scrubCalls++; Assert-OfficeTest (![string]::IsNullOrWhiteSpace($Reason)) 'Recovery must record its reason.'; return 3010 } function Invoke-OfficeProcess { param($FilePath,$Arguments,$LogPrefix) $script:removalCalls++; $script:removalStarted=$true 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','orphan','msi-only','mixed','delayed','remaining','stale','corrupt','corrupt-gone','unknown-17004','read-error','fatal','reboot')) { $script:removalChecks=0; $script:removalCalls=0; $script:removalStarted=$false; $script:scrubCalls=0 $script:removalCode = switch ($script:removalMode) { 'fatal' {1603}; 'reboot' {3010}; 'corrupt' {17004}; 'corrupt-gone' {17004}; 'unknown-17004' {17004}; default {0} } if ($script:removalMode -eq 'remaining') { Assert-OfficeTest ((Remove-OfficeSuite $media $testRoot) -eq 3010) 'Verified leftovers after ODT success must select scrub recovery.' Assert-OfficeTest ($script:removalChecks -eq ((Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts + 2)) 'Remaining Click-to-Run products must be checked for the bounded registration interval.' } elseif ($script:removalMode -eq 'read-error') { Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'Office inventory is unreadable' } elseif ($script:removalMode -in @('fatal','unknown-17004')) { Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'ODT Office removal failed.*automatic scrub was not selected' } else { $result = @(Remove-OfficeSuite $media $testRoot) $expected = if ($script:removalMode -in @('reboot','corrupt','corrupt-gone')) {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','orphan','msi-only')) {0} else {1} Assert-OfficeTest ($script:removalCalls -eq $expectedCalls) 'Run removal only for registered Click-to-Run products, never merely an orphaned service/registry key.' Assert-OfficeTest ($script:scrubCalls -eq $(if ($script:removalMode -in @('corrupt','remaining')) {1} else {0})) 'Only failed removal with products remaining may trigger a single scrub; metadata or no products must not.' } } & { 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.' $credentialCode = $helperAst.Find({ param($node) $node -is [Management.Automation.Language.StringConstantExpressionAst] -and $node.Value -like 'using System;*' }, $true).Value Add-Type -TypeDefinition $credentialCode # Compile only; no credential APIs are called. Assert-OfficeTest ($null -ne ('Emberkom.OfficeCredentials' -as [type])) 'Credential helper failed to compile.' $command = Get-OfficeOneDriveCommand '"C:\Program Files\Microsoft OneDrive\1.2.3\OneDriveSetup.exe" /uninstall /allusers' @('C:\Program Files\Microsoft OneDrive') Assert-OfficeTest ($command.Arguments -eq '/uninstall /allusers') 'OneDrive flags lost.' 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' $null = New-Item -ItemType Directory -Path $cache -Force Set-Content -LiteralPath (Join-Path $cache 'token') -Value 'synthetic' $sentinel = Join-Path $profile 'document.txt'; Set-Content -LiteralPath $sentinel -Value 'preserve' $broker = Join-Path $profile 'AppData\Local\Packages\Microsoft.AAD.BrokerPlugin'; $null = New-Item -ItemType Directory -Path $broker -Force Remove-OfficeProfileCache $profile Assert-OfficeTest (!(Test-Path -LiteralPath $cache)) 'License cache was not deleted.' Assert-OfficeTest ((Test-Path -LiteralPath $sentinel) -and (Test-Path -LiteralPath $broker)) 'Unrelated profile data deleted.' & { function Get-AuthenticodeSignature { [pscustomobject]@{Status=$script:signatureStatus; SignerCertificate=[pscustomobject]@{Subject=$script:signatureSubject}} } $script:signatureStatus='Valid'; $script:signatureSubject='CN=Microsoft Corporation, O=Microsoft Corporation, C=US' Assert-OfficeMicrosoftSignature 'inert.exe' $script:signatureStatus='HashMismatch' Assert-OfficeThrows { Assert-OfficeMicrosoftSignature 'inert.exe' } 'validation failed' $script:signatureStatus='Valid'; $script:signatureSubject='CN=Other, O=Other, C=US' Assert-OfficeThrows { Assert-OfficeMicrosoftSignature 'inert.exe' } 'validation failed' } & { 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'} $script:installCode=3010 Assert-OfficeTest ((Install-OfficeMedia $options $media $testRoot) -eq 3010) 'Setup restart request lost.' $script:installCode=0; $script:installed.ProductReleaseIds='O365ProPlusRetail' Assert-OfficeThrows { Install-OfficeMedia $options $media $testRoot } 'did not match' $script:installed.ProductReleaseIds='O365BusinessRetail'; $script:installed.Platform='x86' Assert-OfficeThrows { Install-OfficeMedia $options $media $testRoot } 'did not match' $script:installed.Platform='x64'; $script:installed.VersionToReport='16.0.0.1' Assert-OfficeThrows { Install-OfficeMedia $options $media $testRoot } 'did not match' $script:installed.VersionToReport='16.0.2.3' Assert-OfficeTest ((Install-OfficeMedia $options $media $testRoot) -eq 0 -and $media.Version -eq '16.0.2.3') 'A newer unpinned build must pass and report the actual installed version.' $options.TargetOfficeVersion='16.0.1.2' Assert-OfficeThrows { Install-OfficeMedia $options $media $testRoot } 'did not match' $script:installed.VersionToReport='16.0.1.2' Assert-OfficeTest ((Install-OfficeMedia $options $media $testRoot) -eq 0 -and $media.Version -eq '16.0.1.2') 'Windows 10 must verify its explicitly selected build.' $options.TargetOfficeVersion='' $script:installed.VersionToReport='invalid' 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 = @() function New-ScheduledTaskAction { param($Execute,$Argument) Assert-OfficeTest ($Execute -like '*\WindowsPowerShell\v1.0\powershell.exe') 'User cleanup must use Windows PowerShell 5.1.'; [pscustomobject]@{Execute=$Execute; Arguments=$Argument} } function New-ScheduledTaskPrincipal { param($UserId,$LogonType,$RunLevel) Assert-OfficeTest ($LogonType -eq 'Interactive' -and $RunLevel -eq 'Limited') 'User task must run limited and interactively.'; $UserId } function New-ScheduledTaskTrigger { param([switch]$AtLogOn,$User) $User } function New-ScheduledTaskSettingsSet { param([switch]$StartWhenAvailable,[switch]$AllowStartIfOnBatteries,[switch]$DontStopIfGoingOnBatteries,$ExecutionTimeLimit,$MultipleInstances) 'settings' } function Register-ScheduledTask { param($TaskName,$Action,$Principal,$Trigger,$Settings,[switch]$Force,$ErrorAction) $script:registered += $TaskName } function Start-ScheduledTask { param($TaskName,$ErrorAction) $script:started += $TaskName } function Get-ScheduledTask { param($TaskName,$ErrorAction) [pscustomobject]@{State='Ready'} } function Get-ItemPropertyValue { param($LiteralPath,$Name,$ErrorAction) if ($LiteralPath -like '*logged-on*') { 'Complete' } } function Unregister-ScheduledTask { param($TaskName,$Confirm,$ErrorAction) $script:removed += $TaskName } $profiles = @([pscustomobject]@{SID='logged-on'; Loaded=$true},[pscustomobject]@{SID='logged-off'; Loaded=$false}) $cleanup = 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 ($cleanup.PendingUserSids.Count -eq 1 -and $cleanup.PendingUserSids[0] -eq 'logged-off' -and $cleanup.RegistrationFailures.Count -eq 0) 'Logged-off user cleanup was reported complete.' function Unregister-ScheduledTask { throw 'Task Scheduler is temporarily unavailable.' } $cleanup = Start-OfficeUserCleanup $profiles ([pscustomobject]@{Helper='C:\secure\helper.ps1'}) (Join-Path $testRoot ('a'*32)) Assert-OfficeTest ($cleanup.PendingUserSids.Count -eq 1 -and $cleanup.PendingUserSids[0] -eq 'logged-off') 'Completed task housekeeping must not fail deployment or mark completed cleanup pending.' function New-ScheduledTaskPrincipal { param($UserId,$LogonType,$RunLevel,$ErrorAction) if ($UserId -eq 'unmapped' -and $script:registrationStage -eq 'principal') { throw 'No mapping between account names and security IDs was done.' } $UserId } function Register-ScheduledTask { param($TaskName,$Action,$Principal,$Trigger,$Settings,[switch]$Force,$ErrorAction) if ($Principal -eq 'unmapped') { throw 'No mapping between account names and security IDs was done.' } $script:registered += $TaskName } $unmapped = [pscustomobject]@{SID='unmapped'; LocalPath='C:\Users\defaultuser100000'; Loaded=$true} foreach ($script:registrationStage in @('principal','register')) { $script:registered=@(); $script:started=@() $cleanup = @(Start-OfficeUserCleanup (@($unmapped) + $profiles) ([pscustomobject]@{Helper='C:\secure\helper.ps1'}) (Join-Path $testRoot ('a'*32)) 2>$null) Assert-OfficeTest ($cleanup.Count -eq 1 -and $cleanup[0].RegistrationFailures.Count -eq 1) 'An unmapped account must return one structured result with a registration failure.' Assert-OfficeTest ($cleanup[0].RegistrationFailures[0].SID -eq 'unmapped' -and $cleanup[0].RegistrationFailures[0].ProfilePath -eq $unmapped.LocalPath -and $cleanup[0].RegistrationFailures[0].Error -match 'No mapping') 'Registration failures must identify the affected SID, profile, and actual error.' Assert-OfficeTest ($script:registered.Count -eq 2 -and $script:started.Count -eq 1) 'An unmapped first profile must not prevent scheduling and starting cleanup for later users.' Assert-OfficeTest ($cleanup[0].PendingUserSids.Count -eq 1 -and $cleanup[0].PendingUserSids[0] -eq 'logged-off') 'A missing task must not be reported as able to retry at sign-in.' } $cleanup = Start-OfficeUserCleanup @() ([pscustomobject]@{Helper='C:\secure\helper.ps1'}) (Join-Path $testRoot ('a'*32)) Assert-OfficeTest ($cleanup.PendingUserSids.Count -eq 0 -and $cleanup.RegistrationFailures.Count -eq 0) 'An empty profile list must return empty cleanup result arrays.' Assert-OfficeTest ((Get-Content -LiteralPath $Global:LogFile -Raw) -match 'Error: User cleanup task registration failed for unmapped \(C:\\Users\\defaultuser100000\)') 'Registration failures must reach the Tools diagnostic log.' } # Classify only current, removal-specific corruption; stale errors in a live # service log and generic 17004 wrappers must not authorize a destructive scrub. & { $path=Join-Path $testRoot 'Office-corruption.log' function Get-OfficeSetupLogFiles { Get-Item -LiteralPath $path } $since=[DateTime]::UtcNow.AddSeconds(-2) $stamp=[DateTime]::Now.ToString('M/d/yyyy H:mm:ss.fff', [Globalization.CultureInfo]::InvariantCulture) $detail='OFFICECL Click-To-Run Non Task Error {"ErrorCode":30034,"ErrorType":"InvalidDirectory","ErrorMessage":"GetFiles: search path root\\integration does not exist","Task":"REMOVEINSTALLATION:{A1D863B9-4F69-45AF-BD5C-D349E5C0C851}"}' Set-Content -LiteralPath $path -Value "$stamp`t$detail" $evidence=Get-OfficeRemovalCorruptionEvidence $since Assert-OfficeTest ($evidence.Path -eq $path -and $evidence.Detail.Contains('root\\integration')) 'The observed InvalidDirectory removal error must trigger recovery evidence.' foreach ($line in @( ('10/22/2026 13:57:00.000' + "`t" + $detail), ("$stamp`t" + $detail.Replace('REMOVEINSTALLATION', 'INSTALL')), ("$stamp`t" + $detail.Replace('InvalidDirectory', 'AccessDenied')), ("$stamp`tSETUP unknown error [ExitCode=17004]"), ('No timestamp ' + $detail), ([DateTime]::Now.AddHours(1).ToString('M/d/yyyy H:mm:ss.fff', [Globalization.CultureInfo]::InvariantCulture) + "`t" + $detail) )) { Set-Content -LiteralPath $path -Value $line Assert-OfficeTest ($null -eq (Get-OfficeRemovalCorruptionEvidence $since)) 'Old, unrelated, unparseable and future evidence must not select recovery.' } function Get-Content { throw 'Log locked' } Assert-OfficeTest ($null -eq (Get-OfficeRemovalCorruptionEvidence $since)) 'Unreadable evidence must not select recovery.' } # Download/extract only on demand, validate the Microsoft executable, and never # rely on Tools.ps1's shadowed Expand-Archive or a previously extracted package. & { Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem $script:scrubPackageMode='single'; $script:scrubSignatures=@(); $script:scrubDownloads=0 function Save-OfficeDownload { param($Uri,$Path) Assert-OfficeTest ($Uri -eq (Get-OfficeDeploymentDefinitions).GetHelpUrl) 'Recovery must use the current Microsoft download link.' $script:scrubDownloads++ $zip=[IO.Compression.ZipFile]::Open($Path, [IO.Compression.ZipArchiveMode]::Create) try { $entries = switch ($script:scrubPackageMode) { 'traversal' { @('../escaped.exe') } 'missing' { @('readme.txt') } 'duplicate' { @('one/GetHelpCmd.exe','two/GetHelpCmd.exe') } default { @('GetHelpCmd.exe','support.dll') } } foreach ($name in $entries) { $entry=$zip.CreateEntry($name); $writer=[IO.StreamWriter]::new($entry.Open()); try { $writer.Write('Inert archive fixture, never executed.') } finally { $writer.Dispose() } } } finally { $zip.Dispose() } } function Assert-OfficeMicrosoftSignature { param($Path) $script:scrubSignatures += $Path; if ($script:scrubPackageMode -eq 'unsigned') { throw 'Invalid Microsoft signature' } } function Expand-Archive { throw 'Must use the literal-path Archive module, not the Tools override.' } foreach ($script:scrubPackageMode in @('single','missing','duplicate','traversal','unsigned')) { $workspace=Join-Path $testRoot ('scrub package [' + $script:scrubPackageMode + ']'); $null=[IO.Directory]::CreateDirectory($workspace) if ($script:scrubPackageMode -eq 'single') { $exe=Initialize-OfficeScrubMedia $workspace Assert-OfficeTest ($exe -eq (Join-Path $workspace 'GetHelp\GetHelpCmd.exe') -and $exe -in $script:scrubSignatures) 'Freshly extracted Get Help must pass signature verification.' $before=$script:scrubDownloads Assert-OfficeThrows { Initialize-OfficeScrubMedia $workspace } 'refusing to reuse' Assert-OfficeTest ($script:scrubDownloads -eq $before) 'A second recovery must not download or reuse its package.' } elseif ($script:scrubPackageMode -eq 'traversal') { Assert-OfficeThrows { Initialize-OfficeScrubMedia $workspace } 'outside the Office deployment root' Assert-OfficeTest (!(Test-Path -LiteralPath (Join-Path $workspace 'escaped.exe'))) 'ZIP extraction must not escape its folder.' } elseif ($script:scrubPackageMode -eq 'unsigned') { Assert-OfficeThrows { Initialize-OfficeScrubMedia $workspace } 'Invalid Microsoft signature' } else { Assert-OfficeThrows { Initialize-OfficeScrubMedia $workspace } 'exactly one GetHelpCmd.exe' } } } # Scrub console details must reach the management log even when no recognizable # scenario code is emitted; excerpts are bounded without altering parser input. & { $prefix=Join-Path $testRoot 'scrub-output' $stdout="Tool startup message without scenario code`n" + (('x' * 2100) + "`n") + ((1..25 | ForEach-Object { "progress $_" }) -join "`n") $stderr='A diagnostic from stderr' [IO.File]::WriteAllText("$prefix.stdout.log", $stdout) [IO.File]::WriteAllText("$prefix.stderr.log", $stderr) $output=@(Read-OfficeScrubOutput $prefix) Assert-OfficeTest ($output.Count -eq 1 -and $output[0] -ceq ($stdout + "`n" + $stderr)) 'Diagnostic excerpts must not change the complete scrub output used for result parsing.' $log=Get-Content -LiteralPath $Global:LogFile -Raw Assert-OfficeTest ($log.Contains('Get Help stderr detail: A diagnostic from stderr') -and $log.Contains('Get Help stdout: ')) 'Both stream sizes and captured text must reach the main management log.' Assert-OfficeTest ($log.Contains('Get Help stdout detail: Tool startup message without scenario code') -and $log.Contains('Get Help stdout detail: progress 25') -and !$log.Contains('Get Help stdout detail: progress 14' + [Environment]::NewLine) -and $log.Contains('[middle output omitted; see full stream log]')) 'Bounded scrub excerpts must retain initial failures and final results.' [IO.File]::WriteAllText("$prefix.stdout.log", 'x' * 2100) [IO.File]::WriteAllText("$prefix.stderr.log", '') $null=Read-OfficeScrubOutput $prefix $log=Get-Content -LiteralPath $Global:LogFile -Raw Assert-OfficeTest ($log.Contains('[truncated; see full stream log]') -and $log.Contains('Get Help stderr: no text captured.')) 'Oversized lines and empty streams must be explicit in the management log.' } # Restore runtime syntax detection instead of trusting stale published switches. & { $usage='GetHelpCmd.exe -S OfficeScrubScenario -AcceptEula' Assert-OfficeTest ((Get-OfficeScrubArguments 0 $usage) -eq '-S OfficeScrubScenario -AcceptEula') 'Current tool usage must omit unsupported OfficeVersion.' Assert-OfficeTest ((Get-OfficeScrubArguments 0 ($usage + "`n -OfficeVersion ")) -eq '-S OfficeScrubScenario -AcceptEula -OfficeVersion All') 'A tool advertising OfficeVersion must request all versions.' Assert-OfficeThrows { Get-OfficeScrubArguments 1 $usage } 'Could not validate' Assert-OfficeThrows { Get-OfficeScrubArguments 0 ($usage + "`nError: Invalid command line arguments") } 'Could not validate' Assert-OfficeThrows { Get-OfficeScrubArguments 0 'No OfficeScrubScenario example' } 'Could not validate' } & { function Get-CimInstance { param($ClassName,$Filter) Assert-OfficeTest ($ClassName -eq 'Win32_Process' -and $Filter.Contains("Name='powershell.exe'")) 'Worker monitoring must inspect detached script hosts.' [pscustomobject]@{Name='powershell.exe';ProcessId=$PID;CommandLine='self'} [pscustomobject]@{Name='powershell.exe';ProcessId=9701;CommandLine='powershell.exe -File C:\Temp\GetHelpElevated\abc\Run.ps1'} [pscustomobject]@{Name='msiexec.exe';ProcessId=9702;CommandLine='msiexec.exe /V'} [pscustomobject]@{Name='OfficeClickToRun.exe';ProcessId=9703;CommandLine='OfficeClickToRun.exe /service'} [pscustomobject]@{Name='OfficeClickToRun.exe';ProcessId=9704;CommandLine='OfficeClickToRun.exe /user'} [pscustomobject]@{Name='msiexec.exe';ProcessId=9705;CommandLine='msiexec.exe /x {fixture}'} } $workers=@(Get-OfficeScrubWorkers) Assert-OfficeTest ($workers.Count -eq 2 -and 9701 -in $workers.ProcessId -and 9705 -in $workers.ProcessId) 'Detached cleanup and active MSI workers matter; the caller and idle service hosts do not.' } # Verify actual process-handle retention using only an inert child, never a scrubber. & { $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes('Start-Sleep -Milliseconds 1500; exit 7')) $probe=Start-Process -FilePath (Join-Path $PSHOME 'powershell.exe') -ArgumentList "-NoProfile -NonInteractive -EncodedCommand $encoded" -WindowStyle Hidden -PassThru $held=$null try { $identity=Get-CimInstance Win32_Process -Filter "ProcessId=$($probe.Id)" -ErrorAction Stop $held=Open-OfficeScrubWorkerHandle $identity Assert-OfficeTest ($held.WaitForExit(10000) -and $held.ExitCode -eq 7) 'A held handle must preserve a failed worker exit after its PID disappears.' Assert-OfficeThrows { Open-OfficeScrubWorkerHandle ([pscustomobject]@{ProcessId=$PID;CreationDate=[datetime]'2000-01-01'}) } 'Process identity changed' } finally { if ($held) { $held.Dispose() }; $probe.Dispose() } } # Captured endpoint report: the launcher returned success, but the worker had # already reported no supported products and was waiting in Console.ReadKey. & { $reports=Join-Path $testRoot 'DAFs'; $null=New-Item -ItemType Directory -Path $reports $reportPath=Join-Path $reports 'cse.amplify.diagaction.gethelp.officeuninstallalda_fixture.log' Copy-Item -LiteralPath (Join-Path $repo 'tests\fixtures\office\scrub-no-products.log') -Destination $reportPath # Copy-Item preserves LastWriteTime; set both times to model a newly written report. [IO.File]::SetCreationTimeUtc($reportPath,[datetime]::UtcNow) [IO.File]::SetLastWriteTimeUtc($reportPath,[datetime]::UtcNow) $worker=[pscustomobject]@{CreationDate=[datetime]::UtcNow.AddMinutes(-1)} $result=@(Read-OfficeScrubWorkerReport $worker @($reports)) Assert-OfficeTest ($result.Count -eq 1 -and $result[0].Result -eq 'Failed' -and $result[0].Detail -eq 'There are no supported Office products installed.') 'Parse the actual failed scrub report, not the launcher success acknowledgment.' $worker.CreationDate=[datetime]::UtcNow.AddMinutes(1) Assert-OfficeTest (@(Read-OfficeScrubWorkerReport $worker @($reports)).Count -eq 0) 'An old report must never be attributed to a new worker.' $worker.CreationDate=[datetime]::UtcNow.AddMinutes(-1) Set-Content -LiteralPath $reportPath -Value 'Report: {"ExecutionResult":' Assert-OfficeTest (@(Read-OfficeScrubWorkerReport $worker @($reports)).Count -eq 0) 'A report being written must not be interpreted as completed.' Set-Content -LiteralPath $reportPath -Value 'Report: {"ExecutionResult":"Failed","TroubleshooterName":"OtherScenario"}' Assert-OfficeTest (@(Read-OfficeScrubWorkerReport $worker @($reports)).Count -eq 0) 'Reports from another scenario must be ignored.' function Invoke-CimMethod { [pscustomobject]@{ReturnValue=0;Sid='S-1-5-18'} } $roots=@(Get-OfficeScrubReportRoots ([pscustomobject]@{ProcessId=9701})) Assert-OfficeTest ($roots.Count -eq 2 -and $roots[0] -like '*systemprofile*\DAFs') 'SYSTEM reports must be sought in both system-profile locations.' function Invoke-CimMethod { [pscustomobject]@{ReturnValue=0;Sid='S-1-fixture'} } function Get-ItemPropertyValue { 'C:\Users\ScrubOwner' } Assert-OfficeTest ((Get-OfficeScrubReportRoots ([pscustomobject]@{ProcessId=9701})) -eq 'C:\Users\ScrubOwner\AppData\Local\DAFs') 'Other worker reports must use that worker owner profile, not the RMM caller profile.' } # A background launch is pending. Workers must finish successfully and removal # state must stay clean for the entire quiet interval; closing early is not success. & { $existing=[pscustomobject]@{Name='powershell.exe';ProcessId=8001;CreationDate=[datetime]'2026-10-29T12:00:00';CommandLine='powershell.exe -NoProfile'} $fixtureScrubWorker=[pscustomobject]@{Name='powershell.exe';ProcessId=9701;CreationDate=[datetime]'2026-10-29T16:00:00';CommandLine='powershell.exe -File C:\Temp\GetHelpElevated\abc\Run.ps1'} function Get-OfficeScrubReportRoots { @() } function Read-OfficeScrubWorkerReport { if ($script:waitMode -eq 'report-failed') { [pscustomobject]@{Result='Failed';Detail='There are no supported Office products installed.';Path='fixture-report.log'} } } function Get-OfficeScrubWorkers { $script:waitPoll++ if ($script:waitMode -eq 'process-error') { throw 'Process inventory unreadable' } $existing if ($script:waitMode -ne 'no-worker' -and ($script:waitPoll -le 2 -or $script:waitMode -eq 'keypress')) { $fixtureScrubWorker } if ($script:waitMode -eq 'quiet-reset' -and $script:waitPoll -eq 5) { [pscustomobject]@{Name='setup.exe';ProcessId=9702;CreationDate=$fixtureScrubWorker.CreationDate;CommandLine='setup.exe'} } } function Open-OfficeScrubWorkerHandle { param($Worker) $script:openCalls++ if ($script:waitMode -eq 'lost-handle') { throw 'Could not monitor scrub worker PID 9701' } $handle=[pscustomobject]@{ExitCode=$(if ($script:waitMode -eq 'closed') {-1073741510} elseif ($script:waitMode -eq 'failed') {1} elseif ($script:waitMode -eq 'restart') {3010} else {0})} $handle | Add-Member ScriptProperty HasExited { $script:waitPoll -gt 2 -and $script:waitMode -ne 'keypress' } $handle | Add-Member ScriptMethod Dispose { $script:disposed++ } $handle } function Get-OfficeSuiteInventory { if ($script:waitMode -eq 'inventory-error') { throw 'Office inventory unreadable' } if ($script:waitMode -eq 'remaining' -or ($script:waitMode -eq 'delayed' -and $script:waitPoll -le 4)) { [pscustomobject]@{DisplayName='Old Office'} } } function Get-OfficeClickToRunState { $script:waitStateReads++ if ($script:waitMode -eq 'state-error') { throw 'Servicing state unreadable' } [pscustomobject]@{SourceReferences=@($(if ($script:waitMode -eq 'stale') {'old-download'}));WorkingConfiguration=@()} } foreach ($script:waitMode in @('success','restart','delayed','quiet-reset','closed','failed','remaining','stale','no-worker','keypress','process-error','inventory-error','report-failed','lost-handle')) { $script:waitPoll=0; $script:disposed=0; $script:openCalls=0; $script:testSleeps=@(); $script:waitStateReads=0 if ($script:waitMode -in @('success','restart','delayed','quiet-reset','stale')) { $result=@(Wait-OfficeScrubRemoval @($existing)) $expectedPolls=switch ($script:waitMode) { 'delayed' {11}; 'quiet-reset' {12}; default {9} } Assert-OfficeTest ($result.Count -eq 0 -and $script:waitPoll -eq $expectedPolls) 'Background verification must wait for workers, delayed removal, and a continuous 60-second quiet interval without leaking output.' } else { $pattern=switch ($script:waitMode) { 'closed' {'exited unsuccessfully.*-1073741510'}; 'failed' {'exited unsuccessfully.*exit 1'}; 'process-error' {'Process inventory unreadable'}; 'inventory-error' {'Office inventory unreadable'}; 'state-error' {'Servicing state unreadable'}; 'lost-handle' {'Could not monitor scrub worker'}; default {'background removal did not finish verification'} } if ($script:waitMode -eq 'keypress') { $pattern = 'Office registrations remaining: 0.*will not resume automatically.*success OR failure' } if ($script:waitMode -eq 'report-failed') { $pattern = 'worker reported failure: There are no supported Office products installed.*fixture-report.log' } Assert-OfficeThrows { Wait-OfficeScrubRemoval @($existing) } $pattern if ($script:waitMode -eq 'keypress') { Assert-OfficeTest ($script:waitStateReads -eq 0) 'A live cleanup worker defers the servicing-state check; it does not prove stale state.' } if ($script:waitMode -eq 'report-failed') { Assert-OfficeTest ($script:waitPoll -eq 1 -and !$script:testSleeps.Count) 'A terminal failed report must stop immediately, without a 30-minute keypress wait.' } if ($script:waitMode -in @('remaining','stale','no-worker','keypress')) { Assert-OfficeTest (($script:testSleeps | Measure-Object -Sum).Sum -eq 1800) 'Unfinished background removal must stop after the restored 30-minute wait.' } } Assert-OfficeTest ($script:disposed -eq $(if ($script:waitMode -in @('process-error','no-worker','lost-handle')) {0} else {1})) 'Every acquired worker handle must be released on success and failure.' Assert-OfficeTest ($script:openCalls -le 1) 'Polling must retain the same worker handle rather than reopening a possibly reused PID.' Assert-OfficeTest ($script:waitStateReads -eq 0) 'Servicing metadata is not a scrub completion criterion.' } } # A scrub requires both a successful scenario/process result and independently # verified removal. Every attempt is bounded to one and cleanup retains its logs. & { $script:scrubLaunches=0 function Initialize-OfficeScrubMedia { param($Workspace) Set-Content -LiteralPath (Join-Path $Workspace 'GetHelp.zip') -Value 'fixture' if ($script:scrubMode -eq 'download') { throw 'Scrub download failed' } Join-Path $Workspace 'GetHelpCmd.exe' } function Invoke-OfficeProcess { param($FilePath,$Arguments,$LogPrefix) if ($Arguments -eq '-?') { $script:usageCalls++ Set-Content -LiteralPath "$LogPrefix.stdout.log" -Value $(if ($script:scrubMode -eq 'bad-help') {'Usage unavailable'} else {'GetHelpCmd.exe -S OfficeScrubScenario -AcceptEula'}) Set-Content -LiteralPath "$LogPrefix.stderr.log" -Value '' return 0 } $script:scrubLaunches++ Assert-OfficeTest ($Arguments -eq '-S OfficeScrubScenario -AcceptEula' -and (Split-Path -Leaf $LogPrefix) -eq 'office-scrub') 'Scrub must use the current tool-supported arguments, omitting the rejected OfficeVersion option.' Set-Content -LiteralPath "$LogPrefix.stdout.log" -Value $script:scrubOutput Set-Content -LiteralPath "$LogPrefix.stderr.log" -Value '' $script:scrubExit } function Get-OfficeScrubWorkers { if ($script:scrubMode -eq 'preexisting-worker') { [pscustomobject]@{Name='powershell.exe';ProcessId=8000;CommandLine='powershell.exe -File C:\Temp\GetHelpElevated\old\Run.ps1'} } } function Wait-OfficeScrubRemoval { param($ExistingWorkers) $script:backgroundWaits++ if ($script:scrubMode -eq 'background-no-worker') { throw 'Get Help background removal did not finish verification within the allowed time.' } } function Get-CimInstance { if ($script:scrubMode -eq 'preexisting-worker') { Get-OfficeScrubWorkers } if ($script:scrubMode -eq 'running') { [pscustomobject]@{Name='GetHelpCmd.exe'} } if ($script:scrubMode -eq 'background') { [pscustomobject]@{Name='powershell.exe';ProcessId=7064;CommandLine='powershell.exe -File C:\Windows\SystemTemp\GetHelpElevated\d509ee113e5346fa82eded7e01f47f69\Run.ps1'} } } function Get-OfficeSuiteInventory { if ($script:scrubMode -eq 'remaining') { [pscustomobject]@{DisplayName='Leftover MSI Office';WindowsInstaller=1} } if ($script:scrubMode -eq 'inventory-error') { throw 'Registry unreadable' } } function Assert-OfficeRemovalComplete { if ($script:scrubMode -eq 'stale') { throw 'Removal verification failed' } } foreach ($script:scrubMode in @('success','restart','download','bad-help','preexisting-worker','failure','not-found-66','not-found-68','empty','invalid-arguments','usage','background','background-no-worker','background-with-00','generic-success','text-error','background-bad-exit','background-error','contradictory','bad-exit','running','remaining','inventory-error','stale')) { $workspace=Join-Path $testRoot ('scrub-result-' + $script:scrubMode); $null=[IO.Directory]::CreateDirectory($workspace) $media=[pscustomobject]@{}; $script:scrubExit=0; $script:scrubOutput='00: Successfully completed this scenario.'; $script:backgroundWaits=0; $script:usageCalls=0 switch ($script:scrubMode) { 'restart' { $script:scrubExit=3010 } 'failure' { $script:scrubOutput='09: Failure to remove Office.' } 'not-found-66' { $script:scrubOutput='66: We could not find the specified Office version.'; $script:scrubExit=66 } 'not-found-68' { $script:scrubOutput='68: We could not find any Office version.' } 'empty' { $script:scrubOutput='' } 'invalid-arguments' { $script:scrubOutput="Starting Microsoft GetHelp Command Line Tool`nError: Invalid command line arguments`nUsage: GetHelpCmd.exe [options]`nExamples:`nGetHelpCmd.exe -S OfficeScrubScenario -AcceptEula" } 'usage' { $script:scrubOutput="Usage: GetHelpCmd.exe [options]`n00: Success" } { $_ -like 'background*' } { $script:scrubOutput="Starting Microsoft GetHelp Command Line Tool`nDiagnostic action completed.`nScenario completed successfully.`nExecutionResultDetails: Uninstall office is running in the background."; if ($_ -eq 'background-with-00') { $script:scrubOutput += "`n00: Success" } } 'generic-success' { $script:scrubOutput='Scenario completed successfully.' } 'text-error' { $script:scrubOutput="Error: Removal failed`nScenario completed successfully." } 'background-error' { $script:scrubOutput += "`nError: Removal failed" } 'background-bad-exit' { $script:scrubExit=1 } 'contradictory' { $script:scrubOutput="09: Failure`n00: Success" } 'bad-exit' { $script:scrubExit=1 } } if ($script:scrubMode -in @('success','restart','generic-success','background-with-00')) { $result=@(Invoke-OfficeScrubRecovery $media $workspace 'fixture corruption') Assert-OfficeTest ($result.Count -eq 1 -and $result[0] -eq 3010 -and $media.ScrubAttempted -and $media.ScrubReason -eq 'fixture corruption') 'Verified scrub must surface its use and restart requirement without leaking log messages.' } else { $pattern=switch ($script:scrubMode) { 'download' {'Scrub download failed'}; 'bad-help' {'Could not validate.*Scrub was not launched'}; 'preexisting-worker' {'Cannot launch scrub.*worker is running'}; 'invalid-arguments' {'rejected its command line.*process 0'}; 'usage' {'rejected its command line.*process 0'}; 'background-no-worker' {'background removal did not finish verification'}; 'background' {'processes are still running'}; 'running' {'processes are still running'}; 'remaining' {'Office remains.*Leftover MSI Office'}; 'inventory-error' {'Registry unreadable'}; 'stale' {'Removal verification failed'}; default {'failed or returned an unverified result'} } Assert-OfficeThrows { Invoke-OfficeScrubRecovery $media $workspace 'fixture corruption' } $pattern } Assert-OfficeTest ($script:usageCalls -eq $(if ($script:scrubMode -eq 'download') {0} else {1})) 'Probe the fresh scrubber usage exactly once, only after recovery was selected.' Assert-OfficeTest ($script:backgroundWaits -eq $(if ($script:scrubMode -in @('background','background-no-worker','background-with-00')) {1} else {0})) 'Only an accepted background launch may enter the completion wait.' $before=$script:scrubLaunches Assert-OfficeThrows { Invoke-OfficeScrubRecovery $media $workspace 'second attempt' } 'already attempted' Assert-OfficeTest ($script:scrubLaunches -eq $before) 'Failure must not create a scrub loop.' $warnings=Complete-OfficeDeploymentFiles $workspace if ($script:scrubMode -in @('running','background','preexisting-worker')) { Assert-OfficeTest ($warnings.Count -gt 0 -and (Test-Path -LiteralPath (Join-Path $workspace 'GetHelp.zip'))) 'Surviving scrub workers must retain in-use media.' } else { Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath (Join-Path $workspace 'GetHelp.zip'))) 'Scrub download must be removed on success and failure.' if ($script:scrubMode -notin @('download','bad-help')) { Assert-OfficeTest (Test-Path -LiteralPath (Join-Path $workspace 'office-scrub.stdout.log')) 'Scrub result logs must survive cleanup.' } } } Assert-OfficeTest (Test-OfficeStagingInUse $testRoot @([pscustomobject]@{Name='cscript.exe';CommandLine='cscript.exe C:\Temp\OffScrubC2R.vbs ALL'})) 'Detached Office scrub scripts must block a new deployment and media cleanup.' } # Get Help's detached signed launcher lives outside the deployment workspace # and can remain at Console.ReadKey after either success or failure. & { $worker=[pscustomobject]@{Name='powershell.exe';ProcessId=7064;CommandLine='"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File C:\Windows\SystemTemp\GetHelpElevated\d509ee113e5346fa82eded7e01f47f69\Run.ps1 C:\Windows\SystemTemp\GetHelpElevated\d509ee113e5346fa82eded7e01f47f69'} $root=Join-Path $testRoot 'detached-gethelp'; $workspace=Join-Path $root ('a'*32) $null=[IO.Directory]::CreateDirectory($workspace) $payload=Join-Path $workspace 'GetHelp.zip'; Set-Content -LiteralPath $payload -Value 'fixture' function Get-CimInstance { $worker } function Get-OfficeDeploymentRoots { $root } function Get-ScheduledTask { throw 'Worker guard must run before retiring tasks.' } Assert-OfficeTest (Test-OfficeStagingInUse $workspace @($worker)) 'GetHelpElevated Run.ps1 must block cleanup despite not naming our workspace.' Assert-OfficeTest (@(Get-OfficeBlockingProcesses $workspace @($worker)).Count -eq 1) 'A worker must be returned once for diagnostics.' Assert-OfficeThrows { Clear-OfficePreviousDeploymentFiles } 'surviving installer.*powershell.exe \(PID 7064\)' $warnings=Complete-OfficeDeploymentFiles $workspace Assert-OfficeTest ($warnings.Count -gt 0 -and (Test-Path -LiteralPath $payload)) 'Detached Get Help workers must preserve media on failure as well as block fresh downloads.' $quoted=[pscustomobject]@{Name='powershell.exe';CommandLine='powershell.exe -File "C:\Temp Folder\GETHELPELEVATED\abc\run.ps1" "C:\Temp Folder\GETHELPELEVATED\abc"'} Assert-OfficeTest (Test-OfficeStagingInUse $workspace @($quoted)) 'Quoted Get Help worker paths must be recognized case-insensitively.' $ordinary=@([pscustomobject]@{Name='powershell.exe';CommandLine='powershell.exe -File C:\Tools\Run.ps1'},[pscustomobject]@{Name='OfficeClickToRun.exe';CommandLine='OfficeClickToRun.exe /service'},[pscustomobject]@{Name='OfficeClickToRun.exe';CommandLine='OfficeClickToRun.exe /user'}) $ordinary += @([pscustomobject]@{Name='msiexec.exe';CommandLine='msiexec.exe /V'},[pscustomobject]@{Name='msiexec.exe';CommandLine='msiexec.exe /Embedding fixture'}) Assert-OfficeTest (!(Test-OfficeStagingInUse $workspace $ordinary)) 'Unrelated PowerShell and idle Click-to-Run/MSI hosts must not block completed cleanup.' Assert-OfficeTest (Test-OfficeStagingInUse $workspace @([pscustomobject]@{Name='msiexec.exe';CommandLine='msiexec.exe /x {fixture} /quiet'})) 'Active MSI uninstall clients must still protect the workspace.' } # Deployment resolves release metadata and deletes it on success or failure. & { $script:historyPaths=@() function Save-OfficeDownload { param($Uri,$Path) Assert-OfficeTest ($Uri -eq (Get-OfficeDeploymentDefinitions).OfficeReleaseHistory) 'Preflight fetched installer media.' $script:historyPaths += $Path [IO.File]::WriteAllText($Path,$script:historyFixture) } $options=Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'} Resolve-OfficeTargetVersion $options $testRoot Assert-OfficeTest ($script:historyPaths.Count -eq 0 -and !$options.TargetOfficeVersion) 'Unpinned preflight must not download release metadata.' $options.OfficeFeatureRelease='2608'; $script:historyFixture=$releaseHistory Resolve-OfficeTargetVersion $options $testRoot Assert-OfficeTest ($options.TargetOfficeVersion -eq '16.0.20326.20158' -and !(Test-Path -LiteralPath $script:historyPaths[-1])) 'Resolved metadata must be removed after successful preflight.' $script:historyFixture='No build' Assert-OfficeThrows { Resolve-OfficeTargetVersion $options $testRoot } 'did not identify' Assert-OfficeTest (!(Test-Path -LiteralPath $script:historyPaths[-1])) 'Failed preflight retained release metadata.' } # Assessment uses HEAD only, follows redirects, requires 200, and never saves data. & { $script:heads=@(); $script:headCode=200; $script:headFails=$false function Invoke-WebRequest { param([switch]$UseBasicParsing,$Method,$Uri,$MaximumRedirection,$TimeoutSec,$ErrorAction,[switch]$OutFile) Assert-OfficeTest ($Method -eq 'Head' -and $MaximumRedirection -eq 10 -and !$OutFile) 'Assessment must use HEAD with redirect handling and no output file.' $script:heads += $Uri if ($script:headFails) { throw 'HEAD unsupported' } [pscustomobject]@{StatusCode=$script:headCode} } function Save-OfficeDownload { throw 'Assessment must not download data.' } $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'} $checks = @(Test-OfficeDownloadLinks $options) Assert-OfficeTest ($checks.Count -eq 7 -and $checks.Count -eq $script:heads.Count) 'HEAD checks must cover ODT discovery, helper, recovery link, CDN, and selected companions.' Assert-OfficeTest ((Get-OfficeDeploymentDefinitions).CompanionInstallers.Teams.Uri -notin $script:heads) 'No-Teams assessment must not probe the Teams download.' $options.InstallTeams=$true; $options.OfficeFeatureRelease='2608'; $script:heads=@() $checks = @(Test-OfficeDownloadLinks $options) Assert-OfficeTest ($checks.Count -eq 9 -and (Get-OfficeDeploymentDefinitions).OfficeReleaseHistory -in $script:heads) 'Windows 10 assessment must check history availability without resolving the build.' $script:headCode=204 Assert-OfficeThrows { Test-OfficeDownloadLinks $options } 'returned 204; expected 200' $script:headFails=$true Assert-OfficeThrows { Test-OfficeDownloadLinks $options } 'HEAD check failed.*HEAD unsupported' $path = Join-Path $testRoot 'not-created\EmberkomOfficeDeployment' $before = @(Get-ChildItem -LiteralPath $testRoot -Force).Count $result = Assert-OfficeWritablePath $path Assert-OfficeTest (!(Test-Path -LiteralPath $path) -and $result.TestedDirectory -eq $testRoot -and @(Get-ChildItem -LiteralPath $testRoot -Force).Count -eq $before) 'Write checks must remove probes and never create deployment directories.' $file = Join-Path $testRoot 'not-a-directory'; Set-Content -LiteralPath $file -Value 'fixture' Assert-OfficeThrows { Assert-OfficeWritablePath $file } 'not a directory' } # Regression: no product is registered, but C2R service/metadata survives. # Exercise the real removal, readiness and installation functions together. & { $script:regressionInstalled=$false; $script:regressionCommands=@() function Get-OfficeSuiteInventory { if ($script:regressionInstalled) { [pscustomobject]@{DisplayName='Click-to-Run: O365BusinessRetail'} } } function Get-OfficeClickToRunState { [pscustomobject]@{Present=$true;SourceReferences=@('C:\Windows\SystemTemp\EmberkomOfficeDeployment\previous\ODT');WorkingConfiguration=@('orphaned-working-marker')} } function Get-CimInstance { @() } function Test-Path { $true } function Get-ItemProperty { [pscustomobject]@{ProductReleaseIds='O365BusinessRetail';Platform='x64';VersionToReport='16.0.20326.20158'} } function Invoke-OfficeScrubRecovery { throw 'Scrub must not run when no product is registered.' } function Invoke-OfficeProcess { param($FilePath,$Arguments,$LogPrefix) $script:regressionCommands += $Arguments Assert-OfficeTest ($Arguments -eq ('/configure "' + $media.Config + '"') -and (Split-Path -Leaf $LogPrefix) -eq 'office-install') 'Only the fresh installation configuration may run in the orphaned-service case.' $script:regressionInstalled=$true 0 } $media=[pscustomobject]@{Setup='inert-setup.exe';Config=(Join-Path $testRoot 'fresh-install.xml');Version='16.0.20326.20158'} $options=[pscustomobject]@{OfficeArchitecture='64';ProductId='O365BusinessRetail';TargetOfficeVersion='16.0.20326.20158'} Assert-OfficeTest ((Remove-OfficeSuite $media $testRoot) -eq 0) 'An orphaned service must skip removal even without a removal configuration.' Assert-OfficeRemovalComplete $testRoot Assert-OfficeTest ((Install-OfficeMedia $options $media $testRoot) -eq 0 -and $script:regressionCommands.Count -eq 1) 'The orphaned-service path must reach and verify the requested installation.' } # Inspect persisted state without touching the actual registry or Office service. & { function Test-Path { return $true } function Get-Item { [pscustomobject]@{PSPath='fixture';Name='ClickToRun'} } function Get-ChildItem { } function Get-Service { [pscustomobject]@{Name='ClickToRunSvc'} } function Get-ItemProperty { [pscustomobject]@{WorkingConfiguration='old-guid';SourcePath='C:\Windows\SystemTemp\EmberkomOfficeDeployment\old\ODT';Platform='x64'} } $state = Get-OfficeClickToRunState Assert-OfficeTest ($state.Present -and $state.WorkingConfiguration[0] -eq 'old-guid' -and $state.SourceReferences.Count -eq 1) 'Interrupted Click-to-Run configuration must be detected without installed products.' function Get-CimInstance { @() } function Get-OfficeSuiteInventory { @() } Assert-OfficeTest (@(Assert-OfficeRemovalComplete $testRoot).Count -eq 0) 'Service, working markers and old source references alone must not block an otherwise idle installation.' function Get-CimInstance { [pscustomobject]@{Name='setup.exe';ProcessId=123;CommandLine='setup.exe /configure remove.xml'} } Assert-OfficeThrows { Assert-OfficeRemovalComplete $testRoot } 'workers are still running' function Get-CimInstance { @() } function Get-OfficeSuiteInventory { [pscustomobject]@{DisplayName='Registered C2R Office'} } Assert-OfficeThrows { Assert-OfficeRemovalComplete $testRoot } 'products remain before replacement' function Get-OfficeSuiteInventory { [pscustomobject]@{DisplayName='MSI Office';WindowsInstaller=1} } Assert-OfficeTest (@(Assert-OfficeRemovalComplete $testRoot).Count -eq 0) 'Legacy MSI products remain assigned to RemoveMSI during installation.' function Get-ItemProperty { [pscustomobject]@{Platform='x64'} } $null = Assert-OfficeRemovalComplete function Get-ItemProperty { throw 'Registry access denied' } Assert-OfficeThrows { Assert-OfficeRemovalComplete } 'Registry access denied' } # Execute the real deferred action with only its live download replaced. & { $id='d'*32; $script:liveHelperId=$null function New-Object { param($TypeName) Assert-OfficeTest ($TypeName -eq 'Net.WebClient') 'Deferred cleanup must fetch its helper live.' $client=[pscustomobject]@{} $client | Add-Member ScriptMethod DownloadString { param($Uri) '# EmberkomOfficeUserCleanup-v5' + [Environment]::NewLine + 'param($DeploymentId) $script:liveHelperId=$DeploymentId' } $client | Add-Member ScriptMethod Dispose { } $client } $command=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String((New-OfficeUserCleanupCommand $id))) & ([scriptblock]::Create($command)) Assert-OfficeTest ($script:liveHelperId -eq $id -and !$command.Contains('-File ')) 'Deferred cleanup must execute freshly fetched source in memory with the correct deployment ID.' } # A new deployment clears every previous GUID workspace, including legacy caches, # while preserving logs and refusing to race a previous installer or user task. & { $root=Join-Path $testRoot 'old-deployments'; $null=[IO.Directory]::CreateDirectory($root) $old=Join-Path $root ('e'*32); $null=[IO.Directory]::CreateDirectory((Join-Path $old 'ODT')) $legacyMetadata=Join-Path $testRoot ('OfficeReleaseHistory-' + ('e'*32) + '.html'); Set-Content -LiteralPath $legacyMetadata -Value 'abandoned metadata' foreach ($name in @('ODT\payload.dat','ODT\native.log','install.xml','remove.xml','options.json','media-cache.json','Office-UserCleanup.ps1','user-cleanup.lock','reinstall-started','result.log')) { Set-Content -LiteralPath (Join-Path $old $name) -Value 'old content, not reusable' } $unknown=Join-Path $root 'unrelated'; $null=[IO.Directory]::CreateDirectory($unknown); Set-Content -LiteralPath (Join-Path $unknown 'keep.txt') -Value 'untouched' function Get-OfficeDeploymentRoots { $root } $script:oldInstaller=$false; $script:oldTaskState='Running'; $script:oldTaskRemoved=$false function Get-CimInstance { if ($script:oldInstaller) { [pscustomobject]@{Name='OfficeClickToRun.exe';CommandLine='OfficeClickToRun.exe platform=x64'} } } function Get-ScheduledTask { if (!$script:oldTaskRemoved) { [pscustomobject]@{TaskName="Emberkom-OfficeCleanup-$('e'*32)-S-1-5-21-123";TaskPath='\';State=$script:oldTaskState} } } function Disable-ScheduledTask { Assert-OfficeTest ($script:oldTaskState -eq 'Ready') 'Only idle tasks may be retired.' } function Unregister-ScheduledTask { $script:oldTaskRemoved=$true } Assert-OfficeThrows { Clear-OfficePreviousDeploymentFiles } 'user cleanup is still running' Assert-OfficeTest (Test-Path -LiteralPath (Join-Path $old 'ODT\payload.dat')) 'Active user tasks must block old-cache cleanup.' $script:oldTaskState='Ready'; $script:oldInstaller=$true Assert-OfficeThrows { Clear-OfficePreviousDeploymentFiles } 'surviving installer' $script:oldInstaller=$false Clear-OfficePreviousDeploymentFiles $remaining=@(Get-ChildItem -LiteralPath $old -Recurse -File) Assert-OfficeTest ($script:oldTaskRemoved -and $remaining.Count -eq 2 -and @($remaining | Where-Object Extension -ne '.log').Count -eq 0) 'Previous cached downloads, options and scripts must be removed; nested logs must remain.' Assert-OfficeTest (!(Test-Path -LiteralPath $legacyMetadata)) 'Abandoned legacy assessment metadata must be removed too.' Assert-OfficeTest (Test-Path -LiteralPath (Join-Path $unknown 'keep.txt')) 'Cleanup must stay within GUID deployment folders.' Clear-OfficePreviousDeploymentFiles Assert-OfficeTest (@(Get-ChildItem -LiteralPath $old -Recurse -File).Count -eq 2) 'Cleanup must be repeatable with logs-only directories.' } # Cleanup runs synchronously on every install exit. Only logs survive in staging; # pending-user tasks retain synchronization state but fetch their helper live. & { $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 (!(Test-Path -LiteralPath (Join-Path $userWorkspace 'Office-UserCleanup.ps1')) -and (Test-Path -LiteralPath (Join-Path $userWorkspace 'user-cleanup.lock'))) 'Pending tasks must retain only synchronization state, never cached code.' $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 (Join-Path $workspace 'ODT')) -and !(Test-Path -LiteralPath (Join-Path $workspace 'odt.exe')) -and (Test-Path -LiteralPath (Join-Path $workspace 'office-install.stdout.log'))) 'Completion must remove media and preserve diagnostics.' Assert-OfficeTest (!(Test-Path -LiteralPath $media.Helper) -and @(Get-ChildItem -LiteralPath $workspace -File | Where-Object Extension -ne '.log').Count -eq 0) 'Deployment cleanup must leave only log files.' Assert-OfficeTest (Test-Path -LiteralPath (Join-Path $userWorkspace 'user-cleanup.lock')) 'Pending-user synchronization state must survive staging cleanup.' $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.' # An installer without a source path, locked media and links all defer cleanup. Assert-OfficeTest (Test-OfficeStagingInUse $workspace @([pscustomobject]@{Name='OfficeC2RClient.exe'})) 'Surviving native installers must defer media cleanup.' Assert-OfficeThrows { Remove-OfficeManagedItem $root $testRoot } 'outside the Office deployment root' Assert-OfficeThrows { Remove-OfficeManagedItem $root $root } 'outside the Office deployment root' $payload=Join-Path $workspace 'odt.exe'; [IO.File]::WriteAllText($payload,'locked') $handle=[IO.File]::Open($payload,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::None) try { $warnings=Complete-OfficeDeploymentFiles $workspace Assert-OfficeTest ($warnings.Count -gt 0 -and (Test-Path -LiteralPath $payload)) 'In-use payload must survive final cleanup.' } finally { $handle.Dispose() } function Get-CimInstance { throw 'Synthetic process inventory failure' } $warnings=Complete-OfficeDeploymentFiles $workspace Assert-OfficeTest ($warnings.Count -gt 0 -and (Test-Path -LiteralPath $payload)) 'Unknown process state must retain media.' } # 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 Assert-OfficeWritablePath { param($Path) [pscustomobject]@{Path=$Path} } function Test-OfficeDownloadLinks { [pscustomobject]@{StatusCode=200;Method='HEAD'} } function Get-OfficeClickToRunState { [pscustomobject]@{Present=$false;SourceReferences=@();WorkingConfiguration=@()} } function Clear-OfficePreviousDeploymentFiles { if ($script:mode -eq 'old-cache') { throw 'Previous artifacts are locked' }; $script:priorCleanupRuns++ } function Assert-OfficeRemovalComplete { if ($script:mode -eq 'readiness-error') { throw 'Removal verification failed' } } function Assert-OfficeDiskSpace { param($Workspace,[switch]$DownloadingMedia) if ($script:mode -eq 'preflight-space') { throw 'Insufficient disk space before download' }; if ($script:mode -eq 'disk-space' -and !$DownloadingMedia) { throw 'Insufficient disk space after staging' } } function Resolve-OfficeTargetVersion { if ($script:mode -eq 'release') { throw 'Release metadata unavailable' } } function Complete-OfficeDeploymentFiles { param($Workspace,$UserWorkspace) $script:artifactCleanupRuns++; if ($script:mode -eq 'download-cleanup') { throw 'Synthetic cleanup failure' }; 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 { $script:workspaceCreates++; $path = Join-Path $testRoot ([guid]::NewGuid().ToString('N')); $null = New-Item -ItemType Directory -Path $path; $path } function Start-Transcript { } function Stop-Transcript { } function Get-CimInstance { [pscustomobject]@{SID='S-1-5-21-test'; LocalPath=$profile; Special=$false} } Set-Content -LiteralPath (Join-Path $profile 'NTUSER.DAT') -Value 'test hive, never loaded' function Stop-OfficeDeploymentApps { $script:events += 'apps' } function Get-OfficeRunningApps { } function Get-OfficeSuiteInventory { if ($script:mode -notin @('office-reboot','scrub-recovery') -or $script:removalStillRegistered) { [pscustomobject]@{DisplayName='Synthetic Office'} } } function Get-OfficeMachineCompanionEntries { if ($script:removalStillRegistered) { [pscustomobject]@{DisplayName='Synthetic OneDrive'} } } function Initialize-OfficeMedia { param($Options,$Workspace) $script:events += 'download'; if ($script:mode -in @('download','download-cleanup')) { throw 'download failure' }; [pscustomobject]@{Version='16.0.1.2'; Helper=(Join-Path $Workspace 'Office-UserCleanup.ps1')} } function Remove-OfficeCompanionApps { $script:events += 'companions'; if ($script:mode -eq 'companions') { throw 'companion failure' }; return ($script:mode -eq 'reboot') } function Remove-OfficeSuite { param($Media,$Workspace) $script:events += 'remove-office' if ($script:mode -eq 'remove-office') { throw 'Office removal failure' } if ($script:mode -eq 'scrub-recovery') { $Media | Add-Member ScrubAttempted $true; $Media | Add-Member ScrubReason 'fixture recovery'; return 3010 } if ($script:mode -eq 'office-reboot') { return 3010 } return 0 } function Clear-OfficeProfileIdentity { $script:events += 'identity'; if ($script:mode -eq 'identity') { throw 'identity failure' } } function Start-OfficeUserCleanup { $script:events += 'user'; if ($script:mode -eq 'user') { throw 'user still running' } $pending = @(); $failures = @() if ($script:mode -in @('pending','registration-and-pending')) { $pending = @('S-1-5-21-test') } if ($script:mode -in @('registration','registration-and-pending','registration-reboot')) { $failures = @([pscustomobject]@{SID='unmapped'; ProfilePath='C:\Users\defaultuser100000'; Error='No mapping'}) } [pscustomobject]@{PendingUserSids=$pending; RegistrationFailures=$failures} } 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'}} } $script:removalStillRegistered=$false $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'; DeferReboot='false'} foreach ($script:mode in @('success','download','download-cleanup','disk-space','companions','remove-office','readiness-error','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','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}; '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 -in @('download','download-cleanup')) { Assert-OfficeTest ('companions' -notin $script:events -and 'remove-office' -notin $script:events) 'Removal ran after download failed.' } if ($script:mode -eq 'download-cleanup') { Assert-OfficeTest ($errorResult.Exception.Message -eq 'download failure') 'Cleanup replaced the original deployment failure.' } if ($script:mode -eq 'disk-space') { Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Low space after staging must stop before app shutdown, removal, identity cleanup, and installation.' } Assert-OfficeTest ($script:artifactCleanupRuns -eq 1) "Finally must attempt media cleanup on every install exit: $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.' } } foreach ($deferScrub in @('true','false')) { $script:mode='scrub-recovery'; $script:events=@() $options=Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium';OfficeAppShutdown='Force';ValidateBeforeChanges='false';DeferReboot=$deferScrub} $result=Invoke-OfficeDeployment $options Assert-OfficeTest ($result.ExitCode -eq 3010 -and $result.ScrubRecoveryAttempted -and $result.ScrubRecoveryReason -eq 'fixture recovery') 'Scrub recovery and restart requirement must be visible in the final receipt.' if ($deferScrub -eq 'true') { Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'Installed' -and 'install' -in $script:events) 'Verified scrub may continue installation when reboot is deferred.' } else { Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'RestartRequiredBeforeInstall' -and 'install' -notin $script:events -and 'identity' -notin $script:events) 'Nondeferred scrub restart must stop before replacement installation and user cleanup.' } } $script:mode='preflight-space'; $script:events=@(); $options.ValidateBeforeChanges=$true; $script:workspaceCreates=0; $script:artifactCleanupRuns=0 Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Insufficient disk space before download' Assert-OfficeTest ($script:events.Count -eq 0 -and $script:workspaceCreates -eq 0 -and $script:artifactCleanupRuns -eq 0) 'Low-space validation must stop without staging or housekeeping.' $options.ValidateBeforeChanges=$false Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Insufficient disk space before download' Assert-OfficeTest ($script:events.Count -eq 0 -and $script:workspaceCreates -eq 0) 'Low-space install must stop before creating a workspace.' $options.ValidateBeforeChanges=$false $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 2 -and $result[0].OfficeDeploymentStatus -eq 'InstalledWithArtifactCleanupPending') 'Unremoved artifacts must report partial completion instead of clean success.' $script:mode='old-cache'; $script:events=@(); $script:workspaceCreates=0 Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Previous artifacts are locked' Assert-OfficeTest ($script:events.Count -eq 0 -and $script:workspaceCreates -eq 0) 'Old artifacts must be cleared before creating or downloading a new deployment.' foreach ($script:mode in @('registration','registration-and-pending','registration-reboot')) { $script:events=@(); $script:artifactCleanupRuns=0 function Install-OfficeMedia { $script:events += 'install'; if ($script:mode -eq 'registration-reboot') { return 3010 }; return 0 } $result = Invoke-OfficeDeployment $options Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'InstalledWithUserCleanupIncomplete' -and $result.UserCleanupRegistrationFailures.Count -eq 1 -and $result.UserCleanupRegistrationFailures[0].SID -eq 'unmapped') 'A task registration failure must remain visible after successful installation.' Assert-OfficeTest ($result.ExitCode -eq $(if ($script:mode -eq 'registration-reboot') {3010} else {2})) 'Registration failures must report partial completion without hiding a required reboot.' Assert-OfficeTest ($result.PendingUserSids.Count -eq $(if ($script:mode -eq 'registration-and-pending') {1} else {0})) 'Unregistered tasks must remain distinct from deferred logon tasks.' Assert-OfficeTest ('install' -in $script:events -and 'install-companions' -in $script:events -and $script:artifactCleanupRuns -eq 1) 'Task registration failure must allow verified installation and staging-file cleanup.' } 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=@(); $script:workspaceCreates=0; $script:artifactCleanupRuns=0; $script:priorCleanupRuns=0 $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.Count -eq 0 -and $script:workspaceCreates -eq 0 -and $script:artifactCleanupRuns -eq 0 -and $script:priorCleanupRuns -eq 0 -and !$result.MediaDownloaded -and !$result.Workspace -and !$result.MetadataResolved) 'Validation downloaded media, created a workspace or reached a deployment action.' Assert-OfficeTest (!$result.TeamsSelected -and $result.ProfileCount -eq 1 -and $result.ExistingOffice[0] -eq 'Synthetic Office') 'Validation report lost the deployment plan.' } } function Get-OfficeRunningApps { [pscustomobject]@{ProcessName='winword'} } $script:events=@() $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'} $result = Invoke-OfficeDeployment $options Assert-OfficeTest ($script:events.Count -eq 0 -and $result.RunningApps[0] -eq 'winword') 'Validation downloaded media or closed a running app with Force selected.' $options.OfficeAppShutdown='Abort'; $script:events=@() Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Apps are running' Assert-OfficeTest ($script:events.Count -eq 0) 'Validation did not stop on an Abort prerequisite failure.' $options.OfficeAppShutdown='Force'; $script:mode='release'; $script:events=@() $result = Invoke-OfficeDeployment $options Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'ValidationPassed' -and !$result.MetadataResolved) 'Assessment must not request release metadata.' $options.ValidateBeforeChanges=$false Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Release metadata unavailable' Assert-OfficeTest ($script:events.Count -eq 0) 'Failed release resolution reached media downloads or app removal.' $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. & { $toolsAst = Read-OfficeAst 'Tools.ps1' $runScript = $toolsAst.Find({param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Run-Script'}, $true) . ([scriptblock]::Create($runScript.Extent.Text)) function IsURLValid { return $true } function New-Object { param([string]$TypeName) if ($TypeName -ne 'Net.WebClient') { throw "Unexpected object in scope test: $TypeName" } $client = [pscustomobject]@{} $client | Add-Member -MemberType ScriptMethod -Name DownloadString -Value { param($URL) '$options = Get-OfficeDeploymentOptions @{OfficeSubscription=$OfficeSubscription; COMPANY=$COMPANY}; $options' } $client } $inertScript = Join-Path $testRoot 'inert.ps1' Set-Content -LiteralPath $inertScript -Value '$options = Get-OfficeDeploymentOptions @{OfficeSubscription=$OfficeSubscription; COMPANY=$COMPANY}; $options' function Download-File { return $inertScript } [string]$OfficeSubscription = 'Microsoft 365 Business Standard'; [string]$COMPANY = 'Caller & Company' $output = @(Run-Script -LivePSScript Install-MicrosoftOffice365) $selected = @($output | Where-Object { $_.PSObject.Properties['ProductId'] }) Assert-OfficeTest ($selected.Count -eq 1 -and $selected[0].ProductId -eq 'O365BusinessRetail' -and $selected[0].Company -eq $COMPANY) 'Run-Script lost RMM caller variables.' } # Run the real shim -> original Run-Script -> main entry point in a child process. # Replace only the destructive workload; mock WebClient rather than making network calls. $toolsAst = Read-OfficeAst 'Tools.ps1' $runScriptText = $toolsAst.Find({param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Run-Script'}, $true).Extent.Text $mockToolsText = $runScriptText + [Environment]::NewLine + (($toolHelpers | ForEach-Object { $_.Extent.Text }) -join [Environment]::NewLine) $workload = $coreAst.Find({param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Invoke-OfficeDeployment'}, $true) $mockWorkload = @' function Invoke-OfficeDeployment { param($Options) 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; DeferReboot=$Options.DeferReboot} } '@ $mockCore = $coreAst.Extent.Text.Remove($workload.Extent.StartOffset, $workload.Extent.EndOffset - $workload.Extent.StartOffset).Insert($workload.Extent.StartOffset, $mockWorkload) $probeTemplate = @' $ErrorActionPreference='Stop' $script:MockTools=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__TOOLS__')) $script:MockCore=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__CORE__')) $script:ProbeMode='__MODE__' $script:ProbeExitCode=__CODE__ $Global:LogFile=Join-Path $PSScriptRoot 'probe-management.log' $values=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__VALUES__')) | ConvertFrom-Json foreach ($property in $values.PSObject.Properties) { Set-Variable -Name $property.Name -Value ([string]$property.Value) } function IsURLValid { $true } function Download-File { param($URL) $path = Join-Path $PSScriptRoot 'downloaded-core.ps1' Set-Content -LiteralPath $path -Value $script:MockCore $path } function New-Object { param([string]$TypeName) if ($TypeName -ne 'Net.WebClient') { throw "Unexpected object: $TypeName" } $client=[pscustomobject]@{} $client | Add-Member -MemberType ScriptMethod -Name DownloadString -Value { param($URL) if ($URL -like '*/Tools.ps1') { return $script:MockTools } if ($URL -like '*/Install-MicrosoftOffice365.ps1') { return $script:MockCore } throw "Unexpected URL: $URL" } $client | Add-Member -MemberType ScriptMethod -Name Dispose -Value { } $client } __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'; 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 $probe = $probeTemplate.Replace('__TOOLS__', (ConvertTo-OfficeTestBase64 $mockToolsText)).Replace('__CORE__', (ConvertTo-OfficeTestBase64 $mockCore)).Replace('__VALUES__', (ConvertTo-OfficeTestBase64 ($probeValues | ConvertTo-Json -Compress))).Replace('__MODE__', $case.Mode).Replace('__CODE__', [string]$case.Code).Replace('__LAUNCH__', $shimSource) $probePath = Join-Path $testRoot 'shim-probe.ps1'; Set-Content -LiteralPath $probePath -Value $probe $ErrorActionPreference='Continue' $probeOutput = & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $probePath 2>&1 $probeExitCode = $LASTEXITCODE $ErrorActionPreference='Stop' Assert-OfficeTest ($probeExitCode -eq $case.Code) "Shim did not propagate workload exit $($case.Code): $probeOutput" $probeText = $probeOutput | Out-String if ($case.Mode -eq 'success') { # Temp/log paths can contain GUID braces; locate the JSON object's line. $receiptStart = [regex]::Match($probeText, '(?m)^\s*\{\s*\r?$') Assert-OfficeTest $receiptStart.Success "Main workload receipt is missing from shim output: $probeText" $receipt = $probeText.Substring($receiptStart.Index) | 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.' } elseif ($case.Mode -eq 'missing') { Assert-OfficeTest ($probeText -match 'did not return a verified result') 'Missing workload receipt was not detected.' } else { Assert-OfficeTest ((Get-Content -LiteralPath (Join-Path $testRoot 'probe-management.log') -Raw) -match 'Error: Office deployment failed: Simulated deployment failure' -and $probeText -match 'Simulated deployment failure') 'Failure must reach both Tools log and Syncro console.' } } # 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); 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. if ([Environment]::Is64BitOperatingSystem) { $entryText = $coreAst.Find({param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Invoke-OfficeDeploymentEntry'}, $true).Extent.Text $nativeProbeTemplate = @' $ErrorActionPreference='Stop' function Get-OfficeDeploymentOptions { param($InputValues) [pscustomobject]$InputValues } function New-OfficeNativeCommand { param($InputValues) 'Write-Host "Native host probe"; [pscustomobject]@{Edition=$PSVersionTable.PSEdition; Version=$PSVersionTable.PSVersion.ToString(); Is64Bit=[Environment]::Is64BitProcess} | ConvertTo-Json -Compress; exit 2' } __ENTRY__ $resultCode=1 Invoke-OfficeDeploymentEntry @{OfficeSubscription='Microsoft/Office 365 E3/E5'} -ExitCode ([ref]$resultCode) exit $resultCode '@ $nativeProbePath = Join-Path $testRoot 'host-probe.ps1'; Set-Content -LiteralPath $nativeProbePath -Value $nativeProbeTemplate.Replace('__ENTRY__', $entryText) $x86PowerShell = Join-Path $env:WINDIR 'SysWOW64\WindowsPowerShell\v1.0\powershell.exe' $ErrorActionPreference='Continue' $hostOutput = & $x86PowerShell -NoProfile -ExecutionPolicy Bypass -File $nativeProbePath 2>&1 $hostExitCode = $LASTEXITCODE $ErrorActionPreference='Stop' Assert-OfficeTest ($hostExitCode -eq 2) '32-bit Syncro host lost the native-host exit code.' $hostText = $hostOutput | Out-String Assert-OfficeTest ($hostText -match 'Native host probe' -and $hostText -notmatch 'CLIXML') 'Native host messages must remain readable in Syncro.' $hostResult = $hostText.Substring($hostText.IndexOf('{')) | ConvertFrom-Json Assert-OfficeTest ($hostResult.Edition -eq 'Desktop' -and $hostResult.Version -like '5.1.*' -and $hostResult.Is64Bit) 'Syncro relaunch must use native Windows PowerShell 5.1.' } Write-Output "PASS: $script:assertions assertions in Windows PowerShell $($PSVersionTable.PSVersion). No downloads, Office changes, credentials, registry writes, or scheduled tasks touched." } finally { $resolved = [IO.Path]::GetFullPath($testRoot) if (!$resolved.StartsWith([IO.Path]::GetFullPath($env:TEMP).TrimEnd('\') + '\OfficeDeploymentTests-', [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe test cleanup target.' } Remove-Item -LiteralPath $resolved -Recurse -Force -ErrorAction Stop }