major improvement to the M365 install process

This commit is contained in:
2026-10-12 18:31:00 -04:00
parent 819b8d72f0
commit 53b55ca0eb
6 changed files with 1459 additions and 66 deletions
+475
View File
@@ -0,0 +1,475 @@
#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, without Tools.ps1's 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') }, $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))
}
}
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', '<Product ID="bogus"/>')) {
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"
}
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeArchitecture='32'; COMPANY='A & B <Company> "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 ($roundTrip.Configuration.Add.OfficeClientEdition -eq '32') '32-bit selection ignored.'
Assert-OfficeTest ($roundTrip.SelectSingleNode('//Property[@Name="SharedComputerLicensing"]').Value -eq '1') 'Shared activation lost.'
Assert-OfficeTest ($roundTrip.Configuration.Add.Version -eq '16.0.12345.67890') 'Downloaded version must be pinned.'
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
& {
$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) { '140.0.0.1' } }
function Invoke-OfficeProcess {
param($FilePath,$Arguments,$LogPrefix)
$script:appCalls += "$FilePath $Arguments"
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 -ne 'missing-Teams') { [pscustomobject]@{DisplayName='MSTeams'; PackageName='MSTeams_1.0.0.0_neutral_~_8wekyb3d8bbwe'; Version='1.0.0.0'} }
if ($script:appMode -ne 'missing-NewOutlook') { [pscustomobject]@{DisplayName='Microsoft.OutlookForWindows'; PackageName='Microsoft.OutlookForWindows_1.0.0.0_neutral_~_8wekyb3d8bbwe'; Version='1.0.0.0'} }
}
function Get-OfficeMachineOneDrive { if ($script:appMode -ne 'missing-OneDrive') { [pscustomobject]@{Path='inert.exe'; Version='26.1.2.3'} } }
function Assert-OfficeMicrosoftSignature { }
$media = @{WebView2='WebView2'; OneDrive='OneDrive'; Teams='Teams'; NewOutlook='NewOutlook'}
foreach ($script:appMode in @('success','reboot','fail-WebView2','fail-OneDrive','fail-Teams','fail-NewOutlook','missing-OneDrive','missing-Teams','missing-NewOutlook')) {
$script:webViewPresent = $false; $script:appCalls = @(); $failure = $null; $result = $null
try { $result = Install-OfficeCompanionApps $media $testRoot -InstallTeams $true } catch { $failure = $_ }
if ($script:appMode -in @('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 -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 "<a href=`"$url`">Download</a> $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 '<html>blocked</html>' } 'unique current ODT'
Assert-OfficeThrows { Get-OfficeOdtDownloadUrl ($url + ' ' + $url.Replace('20326','20327')) } 'unique current ODT'
Assert-OfficeThrows { Get-OfficeOdtDownloadUrl 'https://download.microsoft.com.evil.test/officedeploymenttool_1.exe' } 'unique current ODT'
Assert-OfficeScrubResult 0 '00: Successfully completed this scenario.' @()
Assert-OfficeScrubResult 0 '66: No matching version.' @()
Assert-OfficeThrows { Assert-OfficeScrubResult 0 '09: Failure to remove Office.' @() } 'removal failed'
Assert-OfficeThrows { Assert-OfficeScrubResult 0 'Starting scenario...' @() } 'no recognizable'
Assert-OfficeThrows { Assert-OfficeScrubResult 1 '00: Success.' @() } 'removal failed'
Assert-OfficeThrows { Assert-OfficeScrubResult 0 '68: No product.' @([pscustomobject]@{DisplayName='Office 2016'}) } 'Office remains'
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'
# 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-ItemProperty { return $script:installed }
$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:installCode=42
Assert-OfficeThrows { Install-OfficeMedia $options $media $testRoot } 'installation failed'
}
& {
$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})
$pending = Start-OfficeUserCleanup $profiles ([pscustomobject]@{Helper='C:\secure\helper.ps1'}) (Join-Path $testRoot ('a'*32))
Assert-OfficeTest ($script:registered.Count -eq 2 -and $script:started.Count -eq 1 -and $script:removed.Count -eq 1) 'User scheduling or completed task cleanup is incorrect.'
Assert-OfficeTest ($pending.Count -eq 1 -and $pending[0] -eq 'logged-off') 'Logged-off user cleanup was reported complete.'
}
# Test orchestration with every machine mutation mocked.
& {
function Assert-OfficeDeploymentHost { }
function New-OfficeWorkspace { $path = Join-Path $testRoot ([guid]::NewGuid().ToString('N')); $null = New-Item -ItemType Directory -Path $path; $path }
function Start-Transcript { }
function Stop-Transcript { }
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 { [pscustomobject]@{DisplayName='Synthetic Office'} }
function Initialize-OfficeMedia { $script:events += 'download'; if ($script:mode -eq 'download') { throw 'download failure' }; [pscustomobject]@{Version='16.0.1.2'} }
function Remove-OfficeCompanionApps { $script:events += 'companions'; if ($script:mode -eq 'companions') { throw 'companion failure' }; return ($script:mode -eq 'reboot') }
function Remove-OfficeSuite { $script:events += 'scrub'; if ($script:mode -eq 'scrub') { throw 'scrub failure' } }
function Clear-OfficeProfileIdentity { $script:events += 'identity'; if ($script:mode -eq 'identity') { throw 'identity failure' } }
function Start-OfficeUserCleanup { $script:events += 'user'; if ($script:mode -eq 'user') { throw 'user still running' }; if ($script:mode -eq 'pending') { return ,@('S-1-5-21-test') }; return ,@() }
function Set-OfficeReinstallPhase { $script:events += 'phase'; if ($script:mode -eq 'phase') { throw 'user still holds cleanup lock' } }
function Install-OfficeMedia { $script:events += 'install'; if ($script:mode -eq 'install') { throw 'install failure' }; return 0 }
function Install-OfficeCompanionApps { param($Media,$Workspace,[bool]$InstallTeams) $script:teamsRequested=$InstallTeams; $script:events += 'install-companions'; if ($script:mode -eq 'install-companions') { throw 'companion install failure' }; [pscustomobject]@{ExitCode=$(if ($script:mode -eq 'companion-reboot') {3010} else {0}); Versions=@{NewOutlook='1'; OneDrive='1'}} }
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'}
foreach ($script:mode in @('success','download','companions','scrub','identity','user','phase','install','install-companions','pending','reboot','companion-reboot')) {
$script:events = @(); $errorResult = $null; $result = $null
try { $result = Invoke-OfficeDeployment $options } catch { $errorResult = $_ }
if ($script:mode -in @('success','pending','reboot','companion-reboot')) {
Assert-OfficeTest ($null -eq $errorResult) "Unexpected failure in $script:mode : $errorResult"
$code = switch ($script:mode) { 'success' {0}; 'pending' {2}; 'reboot' {3010}; 'companion-reboot' {3010} }
Assert-OfficeTest ($result.ExitCode -eq $code) "Wrong result code for $script:mode"
} else { Assert-OfficeTest ($null -ne $errorResult) "Failure swallowed in $script:mode" }
if ($script:mode -notin @('success','pending','install','install-companions','companion-reboot')) { Assert-OfficeTest ('install' -notin $script:events) "Install ran after $script:mode failure/reboot." }
if ($script:mode -notin @('success','pending','install-companions','companion-reboot')) { Assert-OfficeTest ('install-companions' -notin $script:events) "Companion install ran after $script:mode failure/reboot." }
if ($script:mode -eq 'download') { Assert-OfficeTest ('companions' -notin $script:events -and 'scrub' -notin $script:events) 'Removal ran after download failed.' }
if ($script:mode -eq 'success') { Assert-OfficeTest (($script:events -join ',') -eq 'download,apps,companions,scrub,identity,user,phase,install,install-companions') 'Deployment order changed.' }
}
$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.'
foreach ($shutdown in @('Abort','Force')) {
foreach ($validate in @($null, '', 'true')) {
$script:events=@()
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeAppShutdown=$shutdown; ValidateBeforeChanges=$validate}
$result = Invoke-OfficeDeployment $options
Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'ValidationPassed' -and $result.ExitCode -eq 0 -and $result.ValidateBeforeChanges) 'Validation did not produce a distinct result.'
Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Validation reached app shutdown, removal, identities, user tasks, phase changes, or installation.'
Assert-OfficeTest (!$result.TeamsSelected -and $result.ProfileCount -eq 1 -and $result.ExistingOffice[0] -eq 'Synthetic Office') 'Validation report lost the deployment plan.'
}
}
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 -join ',') -eq 'download' -and $result.RunningApps[0] -eq 'winword') 'Validation 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='download'; $script:events=@()
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'download failure'
Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Failed validation reached mutations.'
$options.ValidateBeforeChanges='false'
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'validated Boolean'
}
# 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}
}
'@
$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'; 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') {
Assert-OfficeTest ($probeText.IndexOf('{') -ge 0) "Main workload receipt is missing from shim output: $probeText"
$receipt = $probeText.Substring($probeText.IndexOf('{')) | ConvertFrom-Json
Assert-OfficeTest ($receipt.ProductId -eq 'O365ProPlusEEANoTeamsRetail' -and $receipt.Company -ceq $probeValues.COMPANY -and $receipt.Activation -eq 'SharedComputer') 'Shim lost injected strings before main workload.'
Assert-OfficeTest ($receipt.ValidateBeforeChanges -eq ($case.Validate -ne 'false')) 'Shim lost the validation gate.'
$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); 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.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'
$hostOutput = & $x86PowerShell -NoProfile -ExecutionPolicy Bypass -File $nativeProbePath 2>&1
Assert-OfficeTest ($LASTEXITCODE -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
}