# 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-ne5-or$PSVersionTable.PSVersion.Minor-ne1){throw'Run these checks with Windows PowerShell 5.1 (powershell.exe).'}
Assert-OfficeTest($output.Count-eq0-and$script:diskQueries.Count-eq1)'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'
Assert-OfficeTest($result.Version-eq'ready'-and$script:probeCalls-eq3-and$script:testSleeps.Count-eq2)'Delayed registration must return the verified value without leaking log text.'
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.'
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.'
Assert-OfficeTest($output.Count-eq1-and$output[0]-eq17004-and$script:diagnosticCalls-eq1)'ODT native diagnostic collection must retain the original exit code and not pollute output, even when collection fails.'
$old=Join-Path$nativeRoot'Office-old.log';[IO.File]::WriteAllText($old,'Error Old unrelated failure');[IO.File]::SetLastWriteTimeUtc($old,$since.AddHours(-1))
Assert-OfficeTest($output.Count-eq0)'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-eq1)'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.'
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.'
Assert-OfficeTest(@(Write-OfficeSetupDiagnostics-SinceUtc$since-SearchRoots@($nativeRoot)).Count-eq0)'A locked native log must not throw or alter the installer result.'
Assert-OfficeTest($output.Count-eq0)'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.'
Assert-OfficeTest(!$script:appxPresent-and$script:appxCalls-eq$expectedCalls-and$output.Count-eq0)"Appx removal did not recover cleanly: $script:appxMode, provisioned=$provisioned."
Assert-OfficeTest($running.Count-eq3-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-eq0)'Abort must not close any Teams client.'
Assert-OfficeTest($script:stoppedTeams.Count-eq3-and'msteams'-in$script:stoppedTeams)'Force must close the older personal Teams client along with classic/current Teams.'
$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($planin@('Microsoft/Office 365 E3/E5','Microsoft/Office 365 E3/E5 (no Teams)')){
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($planin@('Microsoft 365 Business Premium','Microsoft 365 Business Premium (no Teams)','Microsoft 365 Apps for enterprise')){
$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($valuein@('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.'
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Premium';OfficeArchitecture='32';COMPANY='A & B <Company> "quoted"';OfficeActivation='SharedComputer';OfficeAppShutdown='Force'}
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(!$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-Build19045-ProductType1)-eq'2608')'Windows 10 must select feature release 2608.'
Assert-OfficeTest((Get-OfficeFeatureRelease-Build22631-ProductType1)-eq'')'Windows 11 must remain unpinned.'
Assert-OfficeTest((Get-OfficeFeatureRelease-Build20348-ProductType3)-eq'')'Windows Server must not be mistaken for Windows 10.'
Assert-OfficeTest((Get-OfficeBuildFromHistory$numericHistoryCurrent'2608')-eq'16.0.20326.10')'Build sorting must be numeric and tolerate HTML formatting.'
Assert-OfficeThrows{Get-OfficeBuildFromHistory'<html>Changed Microsoft page</html>'Current'2608'}'did not identify.*Existing Office has not been removed'
foreach($appin@('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-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-CommandExpand-Archive
Assert-OfficeTest($archiveCommand.CommandType-eq'Function'-and!$archiveCommand.Parameters.ContainsKey('LiteralPath'))'The real Tools archive override must be present for this regression.'
Assert-OfficeTest($TimeoutSeconds-eq(Get-OfficeDeploymentDefinitions).OdtPageTimeoutSeconds)'ODT page must use the retried downloader with its configured timeout.'
Assert-OfficeTest($downloadXml.Configuration.Add.GetAttribute('Version')-eq$options.TargetOfficeVersion)'The OS-specific build must be selected before downloading.'
Assert-OfficeTest($media.Version-eq'16.0.12345.67890'-and$media.Companions.Count-eq3-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.'
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.'
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.'
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Standard';OfficeArchitecture='64'}
$script:mediaProcesses=@()
functionAssert-OfficeDiskSpace{param($Workspace,[switch]$DownloadingMedia)Assert-OfficeTest$DownloadingMedia.IsPresent'A fresh download must include staging space.';throw'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.'
Assert-OfficeTest($media.Count-eq4-and$script:staged.Count-eq4-and($script:staged-join',')-eq($script:verified-join','))'Every companion installer must be staged and signed before removal.'
foreach($planin@('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)')){
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.'}
Assert-OfficeTest(!($script:appCalls-match'^WebView2 '))'Existing machine WebView2 runtime was unnecessarily installed.'
foreach($planin@('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)')){
Add-Type-TypeDefinition'using System; public static class OfficeArgumentProbe { public static int Main(string[] args) { Console.Write(String.Join("|", args)); return 0; } }'-OutputAssembly$argumentProbe-OutputTypeConsoleApplication
Assert-OfficeTest($inventory.Count-eq2-and$inventory[0].WindowsInstaller-eq1)'Office inventory must preserve the MSI marker and exclude the Teams add-in.'
functionInvoke-OfficeScrubRecovery{param($Media,$Workspace,$Reason)$script:scrubCalls++;Assert-OfficeTest(![string]::IsNullOrWhiteSpace($Reason))'Recovery must record its reason.';return3010}
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.'
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'
Assert-OfficeTest($result.Count-eq1-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-eq4)'Removal must tolerate registry propagation delays.'}
if($script:removalMode-eq'reboot'){Assert-OfficeTest($script:removalChecks-eq1)'A required restart must be surfaced before demanding registration cleanup.'}
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.'
if(!$behavior){Assert-OfficeTest($script:restartChecks-eq0)'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-eq3)'Deferral must tolerate delayed removal registration.'}
Assert-OfficeTest(Test-OfficeCanDeferRestart([pscustomobject]@{DeferReboot=$true})'Office')'Deferred MSI removal must not block Click-to-Run restart deferral.'
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'}
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-eq1-and$script:removalCalls[0]-like('/x '+$addin.PSChildName+' /qn /norestart*'))'A real machine add-in must still be uninstalled silently.'
$mine=[pscustomobject]@{DisplayName='Microsoft Teams Meeting Add-in for Microsoft Office';Publisher='Microsoft';DisplayVersion='1.26.25904';PSChildName='{11111111-2222-3333-4444-555555555555}'}
Assert-OfficeTest($found.Count-eq1-and$found[0].PSChildName-eq$mine.PSChildName)'User cleanup must discover its HKLM-advertised add-in, deduplicate registry views, and exclude other contexts.'
functionTest-OfficeUserMsiProduct{$false}
Assert-OfficeTest(@(Get-OfficeUserTeamsAddinEntries).Count-eq0)'User cleanup must not claim products registered only for another user or machine.'
Assert-OfficeTest($script:userMsiStarts-eq3-and$script:userMsiChecks-eq3)'User MSI cleanup must recover from busy MSI and delayed registration removal.'
Assert-OfficeTest((Install-OfficeMedia$options$media$testRoot)-eq0-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)-eq0-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'
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.'
functionNew-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}}
functionNew-ScheduledTaskPrincipal{param($UserId,$LogonType,$RunLevel)Assert-OfficeTest($LogonType-eq'Interactive'-and$RunLevel-eq'Limited')'User task must run limited and interactively.';$UserId}
Assert-OfficeTest($script:registered.Count-eq2-and$script:started.Count-eq1-and$script:removed.Count-eq1)'User scheduling or completed task cleanup is incorrect.'
Assert-OfficeTest($cleanup.PendingUserSids.Count-eq1-and$cleanup.PendingUserSids[0]-eq'logged-off'-and$cleanup.RegistrationFailures.Count-eq0)'Logged-off user cleanup was reported complete.'
Assert-OfficeTest($cleanup.PendingUserSids.Count-eq1-and$cleanup.PendingUserSids[0]-eq'logged-off')'Completed task housekeeping must not fail deployment or mark completed cleanup pending.'
functionNew-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.'}
Assert-OfficeTest($cleanup.Count-eq1-and$cleanup[0].RegistrationFailures.Count-eq1)'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-eq2-and$script:started.Count-eq1)'An unmapped first profile must not prevent scheduling and starting cleanup for later users.'
Assert-OfficeTest($cleanup[0].PendingUserSids.Count-eq1-and$cleanup[0].PendingUserSids[0]-eq'logged-off')'A missing task must not be reported as able to retry at sign-in.'
Assert-OfficeTest($cleanup.PendingUserSids.Count-eq0-and$cleanup.RegistrationFailures.Count-eq0)'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.'
$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}"}'
foreach($namein$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()}
}
functionAssert-OfficeMicrosoftSignature{param($Path)$script:scrubSignatures+=$Path;if($script:scrubPackageMode-eq'unsigned'){throw'Invalid Microsoft signature'}}
functionExpand-Archive{throw'Must use the literal-path Archive module, not the Tools override.'}
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'}
Assert-OfficeTest($output.Count-eq1-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.'
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.'
Assert-OfficeTest($workers.Count-eq2-and9701-in$workers.ProcessId-and9705-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.
Assert-OfficeTest($result.Count-eq1-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.'
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.'
if($script:waitMode-eq'report-failed'){[pscustomobject]@{Result='Failed';Detail='There are no supported Office products installed.';Path='fixture-report.log'}}
Assert-OfficeTest($result.Count-eq0-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'){Assert-OfficeTest($script:waitStateReads-eq0)'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-eq1-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-eq1800)'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-le1)'Polling must retain the same worker handle rather than reopening a possibly reused PID.'
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.'
$media=[pscustomobject]@{};$script:scrubExit=0;$script:scrubOutput='00: Successfully completed this scenario.';$script:backgroundWaits=0;$script:usageCalls=0
'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"}
{$_-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"}}
Assert-OfficeTest($result.Count-eq1-and$result[0]-eq3010-and$media.ScrubAttempted-and$media.ScrubReason-eq'fixture corruption')'Verified scrub must surface its use and restart requirement without leaking log messages.'
$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-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.'
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.'
Assert-OfficeTest($warnings.Count-gt0-and(Test-Path-LiteralPath$payload))'Detached Get Help workers must preserve media on failure as well as block fresh downloads.'
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.'
Assert-OfficeTest($options.TargetOfficeVersion-eq'16.0.20326.20158'-and!(Test-Path-LiteralPath$script:historyPaths[-1]))'Resolved metadata must be removed after successful preflight.'
Assert-OfficeTest((Get-OfficeDeploymentDefinitions).CompanionInstallers.Teams.Uri-notin$script:heads)'No-Teams assessment must not probe the Teams download.'
Assert-OfficeTest($checks.Count-eq9-and(Get-OfficeDeploymentDefinitions).OfficeReleaseHistory-in$script:heads)'Windows 10 assessment must check history availability without resolving the build.'
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.'
functionInvoke-OfficeScrubRecovery{throw'Scrub must not run when no product is registered.'}
functionInvoke-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.'
Assert-OfficeTest((Remove-OfficeSuite$media$testRoot)-eq0)'An orphaned service must skip removal even without a removal configuration.'
Assert-OfficeRemovalComplete$testRoot
Assert-OfficeTest((Install-OfficeMedia$options$media$testRoot)-eq0-and$script:regressionCommands.Count-eq1)'The orphaned-service path must reach and verify the requested installation.'
Assert-OfficeTest($state.Present-and$state.WorkingConfiguration[0]-eq'old-guid'-and$state.SourceReferences.Count-eq1)'Interrupted Click-to-Run configuration must be detected without installed products.'
Assert-OfficeTest(@(Assert-OfficeRemovalComplete$testRoot).Count-eq0)'Service, working markers and old source references alone must not block an otherwise idle installation.'
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.
foreach($namein@('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'}
Assert-OfficeTest($script:oldTaskRemoved-and$remaining.Count-eq2-and@($remaining|Where-ObjectExtension-ne'.log').Count-eq0)'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-eq2)'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.
Assert-OfficeTest($Root-eq(Join-Path$env:ProgramData'EmberkomOfficeDeployment')-and$DeploymentId-eq('c'*32))'Pending-user helper must use a separate protected ProgramData 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.'
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-ObjectExtension-ne'.log').Count-eq0)'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.'
# 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'
functionAssert-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'}}
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Premium';OfficeAppShutdown='Force';ValidateBeforeChanges='false';DeferReboot='false'}
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.'}
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.'}
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Premium';OfficeAppShutdown='Force';ValidateBeforeChanges='false';DeferReboot=$deferScrub}
$result=Invoke-OfficeDeployment$options
Assert-OfficeTest($result.ExitCode-eq3010-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.'}
Assert-OfficeThrows{Invoke-OfficeDeployment$options}'Insufficient disk space before download'
Assert-OfficeTest($script:events.Count-eq0-and$script:workspaceCreates-eq0-and$script:artifactCleanupRuns-eq0)'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-eq0-and$script:workspaceCreates-eq0)'Low-space install must stop before creating a workspace.'
Assert-OfficeTest($result.Count-eq1-and$result[0].ArtifactCleanupPending-and$result[0].ExitCode-eq2-and$result[0].OfficeDeploymentStatus-eq'InstalledWithArtifactCleanupPending')'Unremoved artifacts must report partial completion instead of clean success.'
Assert-OfficeThrows{Invoke-OfficeDeployment$options}'Previous artifacts are locked'
Assert-OfficeTest($script:events.Count-eq0-and$script:workspaceCreates-eq0)'Old artifacts must be cleared before creating or downloading a new deployment.'
Assert-OfficeTest($result.OfficeDeploymentStatus-eq'InstalledWithUserCleanupIncomplete'-and$result.UserCleanupRegistrationFailures.Count-eq1-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-eq1)'Task registration failure must allow verified installation and staging-file cleanup.'
$options=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft 365 Business Premium';OfficeAppShutdown='Force';ValidateBeforeChanges='false'}
$result=Invoke-OfficeDeployment$options
Assert-OfficeTest($result.ExitCode-eq3010-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.'
$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.'
$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-eq0-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-eq0-and$script:workspaceCreates-eq0-and$script:artifactCleanupRuns-eq0-and$script:priorCleanupRuns-eq0-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-eq1-and$result.ExistingOffice[0]-eq'Synthetic Office')'Validation report lost the deployment plan.'
Assert-OfficeTest($script:events.Count-eq0-and$result.RunningApps[0]-eq'winword')'Validation downloaded media or closed a running app with Force selected.'
Assert-OfficeTest($selected.Count-eq1-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.
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($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.
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.
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.'}