# 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($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-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($roundTrip.Configuration.Add.Version-eq'16.0.12345.67890')'Downloaded version must be pinned.'
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($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.Version-eq$media.Version)'Staged configuration must pin 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'))'Unattended deployments must not stage an interactive scrubber.'
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.'
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-OfficeThrows{Remove-OfficeSuite$media$testRoot}'Office remains.*Office Home and Business 2021.*manual scrub'
Assert-OfficeTest($script:removalChecks-eq((Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts+2))'Remaining Click-to-Run products must be checked for the bounded registration interval.'
}elseif($script:removalMode-eq'read-error'){
Assert-OfficeThrows{Remove-OfficeSuite$media$testRoot}'Office inventory is unreadable'
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)'Do not remove absent Click-to-Run Office, rerun failed removal, or launch a fallback scrubber.'
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-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.'
Assert-OfficeTest(!(Restore-OfficeMediaCache$different$target))'Teams selection mismatch reused the wrong cache.'
$different=Get-OfficeDeploymentOptions@{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)';OfficeArchitecture='64';UpdateChannel='MonthlyEnterprise'}
Assert-OfficeTest(!(Restore-OfficeMediaCache$different$target))'Channel mismatch reused the wrong cache.'
Assert-OfficeThrows{Restore-OfficeMediaCache$options$target}'previous Office deployment still has active processes'
Assert-OfficeTest(Test-Path-LiteralPath$stream)'A live installer lost its cached media.'
functionGet-CimInstance{}
$script:rejectCacheSignature=$true
Assert-OfficeTest(!(Restore-OfficeMediaCache$options$target))'Invalid Microsoft signature was reused.'
$script:rejectCacheSignature=$false
$media=Initialize-OfficeMedia$options$target
Assert-OfficeTest($media.CachedMediaReused-and$media.Version-eq'16.0.12345.67890'-and$script:helperDownloads-eq1)'Deployment did not reuse the validated media and refresh the helper.'
Assert-OfficeTest(!(Test-Path-LiteralPath(Join-Path$source'ODT'))-and(Test-Path-LiteralPath$media.Setup))'Cache transfer duplicated large files or lost setup.'
Assert-OfficeTest($config.Configuration.AppSettings.Setup.Value-eq'New Company'-and$config.Configuration.Add.SourcePath-eq(Join-Path$target'ODT'))'Reused media retained stale company/configuration paths.'
Assert-OfficeTest($Root-eq(Join-Path$env:ProgramData'EmberkomOfficeDeployment')-and$DeploymentId-eq('c'*32))'Pending-user helper must use a separate protected ProgramData workspace.'
Assert-OfficeTest($media.Helper-eq(Join-Path$userWorkspace'Office-UserCleanup.ps1')-and(Test-Path-LiteralPath$media.Helper))'User helper was not separated from cached installers.'
Assert-OfficeTest(!$warnings.Count-and!(Test-Path-LiteralPath(Join-Path$legacy'odt.exe'))-and(Test-Path-LiteralPath(Join-Path$legacy'Office-UserCleanup.ps1')))'Legacy download cleanup lost pending-user state or left old downloads.'
}
# The legacy uninstaller must delete both successful and partial downloads.
functionComplete-OfficeDeploymentFiles{param($Workspace,$UserWorkspace,$PreviousRoot)$script:artifactCleanupRuns++;if($script:mode-eq'cleanup-warning'){return,@('Synthetic file in use')};return,@()}
$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-eq'download'){Assert-OfficeTest('companions'-notin$script:events-and'remove-office'-notin$script:events)'Removal ran after download failed.'}
Assert-OfficeTest($script:artifactCleanupRuns-eq$(if($script:mode-in@('success','pending','companion-reboot')){1}else{0}))"Media cleanup ran before successful installation, or was skipped after success: $script:mode"
if($script:mode-eq'office-reboot'){Assert-OfficeTest($result.OfficeDeploymentStatus-eq'RestartRequiredBeforeInstall'-and'identity'-notin$script:events-and'user'-notin$script:events)'Office removal restart must stop before user cleanup and replacement installation.'}
if($script:mode-eq'success'){Assert-OfficeTest(($script:events-join',')-eq'download,apps,companions,remove-office,identity,user,phase,install,install-companions')'Deployment order changed.'}
}
$script:mode='cleanup-warning';$script:events=@()
$result=@(Invoke-OfficeDeployment$options)
Assert-OfficeTest($result.Count-eq1-and$result[0].ArtifactCleanupPending-and$result[0].ExitCode-eq0-and$result[0].OfficeDeploymentStatus-eq'Installed')'Artifact cleanup problems corrupted the receipt or failed a verified installation.'
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-join',')-eq'download')'Validation reached app shutdown, removal, identities, user tasks, phase changes, or installation.'
Assert-OfficeTest(!$result.TeamsSelected-and$result.ProfileCount-eq1-and$result.ExistingOffice[0]-eq'Synthetic Office')'Validation report lost the deployment plan.'
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.'}