From 53b55ca0ebb29afa9b2865f523305fe36947e42e Mon Sep 17 00:00:00 2001 From: ek-dyoder Date: Mon, 12 Oct 2026 18:31:00 -0400 Subject: [PATCH] major improvement to the M365 install process --- Install-MicrosoftOffice365.ps1 | 760 +++++++++++++++++++-- README.md | 4 + docs/Office365-Deployment.md | 124 ++++ resources/office/Office-UserCleanup.ps1 | 140 ++++ rmm/Install-MicrosoftOffice365.ps1 | 22 +- tests/Install-MicrosoftOffice365.Tests.ps1 | 475 +++++++++++++ 6 files changed, 1459 insertions(+), 66 deletions(-) create mode 100644 docs/Office365-Deployment.md create mode 100644 resources/office/Office-UserCleanup.ps1 create mode 100644 tests/Install-MicrosoftOffice365.Tests.ps1 diff --git a/Install-MicrosoftOffice365.ps1 b/Install-MicrosoftOffice365.ps1 index 267ab8f..3324a2b 100644 --- a/Install-MicrosoftOffice365.ps1 +++ b/Install-MicrosoftOffice365.ps1 @@ -1,70 +1,706 @@ -# $COMPANY must be supplied by RMM -$PRODUCT = 'O365ProPlusRetail' -$BITNESS = '64' -$MIGARCH = 'TRUE' -$CHANNEL = 'SemiAnnual' -$UPDATES = 'TRUE' -$DISPLAY = 'None' # "None", "Full" -$ACCEULA = 'TRUE' +#Requires -Version 5.1 +<# + Validates by default; destructive clean deployment requires ValidateBeforeChanges=false. + Run elevated in Windows PowerShell 5.1 with Tools.ps1 loaded. + Inputs are inherited from the RMM caller; no script-level param block. + See docs/Office365-Deployment.md for Syncro dropdowns and cleanup boundaries. +#> -# Make changes if the system is 32bit -If ( !(Is64Bit) ) { $BITNESS = '32'; $MIGARCH = 'FALSE' } - -$CONFIG = @" - - - - - - - - - - - - - - - - - - - -"@ - -# Set path to temp directory -$TEMPDIR = '{0}microsoft-office-deployment' -f (Get-TempPath) - -# Recursively delete $TEMPDIR if it already exists -If ( Test-Path $TEMPDIR ) { - Write-Output """${TEMPDIR}"" already exists and will be deleted" - Try { Remove-Item -Path $TEMPDIR -Recurse -Force -ErrorAction SilentlyContinue } - Catch { Write-Error $_.Exception.Message } +function Get-OfficeDeploymentDefinitions { + # Maintenance surface: edit Microsoft's deployment contracts here, not a separate file. + # Evergreen URLs avoid pinning installer releases. Product/license mappings remain explicit. + @{ + Plans = @{ + 'Microsoft 365 Business Standard' = 'O365BusinessRetail' + 'Microsoft 365 Business Premium' = 'O365BusinessRetail' + 'Microsoft 365 Apps for business' = 'O365BusinessEEANoTeamsRetail' + 'Microsoft 365 Business Standard (no Teams)' = 'O365BusinessEEANoTeamsRetail' + 'Microsoft 365 Business Premium (no Teams)' = 'O365BusinessEEANoTeamsRetail' + 'Microsoft 365 Apps for enterprise' = 'O365ProPlusEEANoTeamsRetail' + 'Microsoft/Office 365 E3/E5' = 'O365ProPlusRetail' + 'Microsoft/Office 365 E3/E5 (no Teams)' = 'O365ProPlusEEANoTeamsRetail' + } + TeamsProducts = @('O365BusinessRetail', 'O365ProPlusRetail') + SharedComputerBusinessPlans = @('Microsoft 365 Business Premium', 'Microsoft 365 Business Premium (no Teams)') + Choices = @{ + OfficeArchitecture = @('Auto', '64', '32') + UpdateChannel = @('Current', 'MonthlyEnterprise', 'SemiAnnual') + OfficeActivation = @('User', 'SharedComputer') + OfficeAppShutdown = @('Abort', 'Force') + } + RepositoryRoot = 'https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master' + OdtPage = 'https://www.microsoft.com/en-us/download/details.aspx?id=49117' + OdtDownloadPattern = 'https://download\.microsoft\.com/[^"\s<>]+/officedeploymenttool_[a-zA-Z0-9_-]+\.exe' + GetHelpUrl = 'https://aka.ms/SaRA_EnterpriseVersionFiles' + GetHelpExecutable = 'GetHelpCmd.exe' + ScrubArguments = '-S OfficeScrubScenario -AcceptEula -OfficeVersion All' + ScrubScenarioPattern = '(?m)^\s*(\d{2}):' + ScrubScenarioSuccess = @('00', '66', '68') + ScrubExitSuccess = @(0, 66, 68) + HelperVersion = 'EmberkomOfficeUserCleanup-v2' + Language = 'en-us' + OfficeBuildPattern = '^16\.0\.\d+\.\d+$' + OdtExcludedApps = @('Groove', 'OneDrive', 'Lync', 'Teams', 'OutlookForWindows') + CompanionInstallers = @{ + WebView2 = @{ File='MicrosoftEdgeWebview2Setup.exe'; Uri='https://go.microsoft.com/fwlink/p/?LinkId=2124703'; Arguments='/silent /install' } + Teams = @{ File='teamsbootstrapper.exe'; Uri='https://go.microsoft.com/fwlink/?linkid=2243204&clcid=0x409'; Arguments='-p'; Package='MSTeams' } + NewOutlook = @{ File='OutlookSetup.exe'; Uri='https://go.microsoft.com/fwlink/?linkid=2207851'; Arguments='--provision true --quiet --start-'; Package='Microsoft.OutlookForWindows' } + OneDrive = @{ File='OneDriveSetup.exe'; Arguments='/allusers /silent'; Uris=@{ + ARM64='https://go.microsoft.com/fwlink/?linkid=2282608' + x64='https://go.microsoft.com/fwlink/?linkid=844652' + x86='https://go.microsoft.com/fwlink/?linkid=2181213' + } } + } + WebViewClientId = '{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' + AppxPublisherSuffix = '_8wekyb3d8bbwe' + MinimumWindowsBuild = 19041 + MinimumServerBuild = 20348 + MinimumServerRevision = 2402 + Windows11Build = 22000 + TeamsUnsupportedWindows10Editions = @('EnterpriseS', 'EnterpriseSN', 'IoTEnterpriseS') + RunningAppNames = @('lync', 'winword', 'excel', 'msaccess', 'mstore', 'infopath', 'setlang', 'msouc', 'ois', 'onenote', 'outlook', 'powerpnt', 'mspub', 'groove', 'visio', 'winproj', 'graph', 'teams', 'ms-teams', 'OneDrive', 'olk') + AppxRemovalNames = @('Microsoft.Office.Desktop', 'Microsoft.MicrosoftOfficeHub', 'Microsoft.Office.OneNote', 'Microsoft.OutlookForWindows', 'MSTeams', 'MicrosoftTeams') + TeamsMsiNames = @('Teams Machine-Wide Installer', 'Microsoft Teams Meeting Add-in for Microsoft Office') + OfficeIdentityVersions = @('15.0', '16.0') + OfficeIdentityKeys = @('Identity', 'Licensing') + OfficeCachePaths = @('AppData\Local\Microsoft\Office\Licenses', 'AppData\Local\Microsoft\Office\16.0\Licensing', 'AppData\Local\Microsoft\Office\15.0\Licensing') + DownloadAttempts = 3 + DownloadTimeoutSeconds = 300 + DownloadRetrySeconds = 3 + OdtPageTimeoutSeconds = 120 + UserCleanupWaitMinutes = 5 + UserCleanupTaskMinutes = 15 + } } -# Create $TEMPDIR -Write-Output "Creating: ${TEMPDIR}" -Try { New-Item -Path $TEMPDIR -ItemType Directory -Force -ErrorAction Stop } -Catch { Write-Error $_.Exception.Message ; Return } +function Get-OfficeDeploymentOptions { + param([hashtable]$InputValues) + $definitions = Get-OfficeDeploymentDefinitions + $plans = $definitions.Plans + # ConvertTo-RmmBoolean treats blank as false; this destructive workflow must default to true. + [string]$validate = $InputValues.ValidateBeforeChanges + if ([string]::IsNullOrWhiteSpace($validate)) { $validate = 'true' } + $validateOnly = ConvertTo-RmmBoolean -Value $validate -VariableName 'ValidateBeforeChanges' + [string]$subscription = $InputValues.OfficeSubscription + $subscription = $subscription.Trim() + # Accept previously documented individual names for existing saved RMM selections. + if ($subscription -match '^(Microsoft|Office) 365 E[35]( \(no Teams\))?$') { + $subscription = 'Microsoft/Office 365 E3/E5' + $Matches[2] + } + if (!$plans.ContainsKey($subscription)) { + throw "Select a supported OfficeSubscription. '$subscription' is not supported. Business Basic, E1, and frontline/web-only plans do not license this desktop suite." + } + $choices = $definitions.Choices + [string]$company = $InputValues.COMPANY + $company = $company.Trim() + if ($company -eq 'None') { $company = '' } + $options = @{ OfficeSubscription = $subscription; ProductId = $plans[$subscription]; Company = $company; ValidateBeforeChanges = $validateOnly } + # Derive this from the validated product mapping, including standalone Apps plans and legacy aliases. + $options.InstallTeams = $options.ProductId -in $definitions.TeamsProducts + foreach ($name in $choices.Keys) { + [string]$value = $InputValues[$name] + $value = $value.Trim() + if (!$value) { $value = $choices[$name][0] } + if ($value -notin $choices[$name]) { throw "Invalid ${name}: '$value'. Allowed: $($choices[$name] -join ', ')." } + $options[$name] = $value + } + if ($options.OfficeActivation -eq 'SharedComputer' -and $options.ProductId -like 'O365Business*' -and $subscription -notin $definitions.SharedComputerBusinessPlans) { + throw 'Shared computer activation requires Business Premium or an eligible enterprise subscription.' + } + if ($options.OfficeArchitecture -eq 'Auto') { $options.OfficeArchitecture = if ([Environment]::Is64BitOperatingSystem) { '64' } else { '32' } } + if ($options.OfficeArchitecture -eq '64' -and ![Environment]::Is64BitOperatingSystem) { throw '64-bit Office requires 64-bit Windows.' } + if ($options.OfficeArchitecture -eq '32' -and ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64' -or $env:PROCESSOR_ARCHITEW6432 -eq 'ARM64')) { throw '32-bit Office is not supported on Windows ARM64.' } + [pscustomobject]$options +} -# Write $CONFIG to config.xml -$CONFIGFILE = "${TEMPDIR}\config.xml" -Try { $CONFIG | WriteToFile_UTF8NoBOM -FilePath "${CONFIGFILE}" } -Catch { Write-Output "Cannot write configuration file! This script will exit." ; Write-Error $_.Exception.Message ; Return } +function Assert-OfficeDeploymentHost { + param($Options) + $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) + if (!$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Office deployment requires SYSTEM or an elevated administrator.' } + if ([Environment]::Is64BitOperatingSystem -and ![Environment]::Is64BitProcess) { throw 'Office deployment must run in native Windows PowerShell; the main script entry point handles relaunch.' } + if ($PSVersionTable.PSEdition -ne 'Desktop' -or $PSVersionTable.PSVersion.Major -ne 5 -or $PSVersionTable.PSVersion.Minor -ne 1) { throw 'Run in Windows PowerShell 5.1 for Appx support.' } + foreach ($command in @('Get-AppxPackage', 'Remove-AppxPackage', 'Get-AppxProvisionedPackage', 'Remove-AppxProvisionedPackage', 'Register-ScheduledTask')) { $null = Get-Command $command -ErrorAction Stop } + $os = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop + $windows = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction Stop + Assert-OfficeCompanionPlatform -Build ([int]$os.BuildNumber) -ProductType ([int]$os.ProductType) -Revision ([int]$windows.UBR) -EditionId $windows.EditionID -InstallTeams $Options.InstallTeams +} -# Set the name of ODT setup utility -$ODT = "${TEMPDIR}\setup.exe" +function Assert-OfficeCompanionPlatform { + param([int]$Build, [int]$ProductType, [int]$Revision, [string]$EditionId, [bool]$InstallTeams = $false) + $definitions = Get-OfficeDeploymentDefinitions + if ($Build -lt $definitions.MinimumWindowsBuild) { throw "Teams and new Outlook require Windows build $($definitions.MinimumWindowsBuild) or newer. No apps have been removed." } + if ($ProductType -ne 1 -and ($Build -lt $definitions.MinimumServerBuild -or ($Build -eq $definitions.MinimumServerBuild -and $Revision -lt $definitions.MinimumServerRevision))) { throw "New Outlook requires Windows Server 2022 build $($definitions.MinimumServerBuild).$($definitions.MinimumServerRevision) or newer. No apps have been removed." } + if ($InstallTeams -and $ProductType -eq 1 -and $Build -lt $definitions.Windows11Build -and $EditionId -in $definitions.TeamsUnsupportedWindows10Editions) { throw 'Teams desktop does not support Windows 10 LTSC. No apps have been removed.' } +} -# Download ODT -Write-Output "Downloading Office Deployment Tool" -Download-File -URL 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/setup-exe/download/setup.exe' -File $ODT +function New-OfficeWorkspace { + # Executable content must never be writable by a standard user. + $root = Join-Path $env:ProgramData 'EmberkomOfficeDeployment' + $null = New-Item -ItemType Directory -Path $root -Force -ErrorAction Stop + for ($item = Get-Item -LiteralPath $root -Force; $null -ne $item; $item = $item.Parent) { + if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Deployment path traverses a reparse point: $($item.FullName)" } + } + $acl = New-Object Security.AccessControl.DirectorySecurity + $acl.SetAccessRuleProtection($true, $false) + foreach ($sid in @('S-1-5-18', 'S-1-5-32-544', 'S-1-5-32-545')) { + $rights = if ($sid -eq 'S-1-5-32-545') { 'ReadAndExecute' } else { 'FullControl' } + $rule = New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)), $rights, 'ContainerInherit,ObjectInherit', 'None', 'Allow') + $acl.AddAccessRule($rule) + } + $acl.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544'))) + Set-Acl -LiteralPath $root -AclObject $acl -ErrorAction Stop + $path = Join-Path $root ([guid]::NewGuid().ToString('N')) + $null = New-Item -ItemType Directory -Path $path -ErrorAction Stop + $null = New-Item -ItemType File -Path (Join-Path $path 'user-cleanup.lock') -ErrorAction Stop + $path +} -# Install Office -Write-Output "Installing Microsoft Office" -Try { Start-Process $ODT -ArgumentList "/configure ""${CONFIGFILE}""" -Wait } -Catch { Write-Error $_.Exception.Message } +function Assert-OfficeMicrosoftSignature { + param([string]$Path) + $signature = Get-AuthenticodeSignature -LiteralPath $Path -ErrorAction Stop + if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch '(^|,\s*)O=Microsoft Corporation(,|$)') { throw "Microsoft Authenticode validation failed: $Path ($($signature.Status))." } + $null = Write-Output "Verified Microsoft signature: $Path" +} -# Cleanup -Write-Output "Deleting temp directory and its contents" -Try { Remove-Item -Path $TEMPDIR -Recurse -Force -ErrorAction SilentlyContinue } -Catch { Write-Error $_.Exception.Message } +function Save-OfficeDownload { + param([string]$Uri, [string]$Path) + $definitions = Get-OfficeDeploymentDefinitions + for ($attempt = 1; $attempt -le $definitions.DownloadAttempts; $attempt++) { + try { + $null = Write-Output "Download attempt ${attempt}: $Uri -> $Path" + Invoke-WebRequest -UseBasicParsing -Uri $Uri -OutFile $Path -TimeoutSec $definitions.DownloadTimeoutSeconds -ErrorAction Stop + if ((Get-Item -LiteralPath $Path -ErrorAction Stop).Length -eq 0) { throw 'Download was empty.' } + return + } catch { + Write-Error "Download attempt $attempt failed: $($_.Exception.Message)" -ErrorAction Continue + if ($attempt -eq $definitions.DownloadAttempts) { throw } + Start-Sleep -Seconds ($definitions.DownloadRetrySeconds * $attempt) + } + } +} + +function Get-OfficeOdtDownloadUrl { + param([string]$PageContent) + $content = [Net.WebUtility]::HtmlDecode($PageContent).Replace('\/', '/') + $urls = @([regex]::Matches($content, (Get-OfficeDeploymentDefinitions).OdtDownloadPattern) | ForEach-Object { $_.Value } | Select-Object -Unique) + if ($urls.Count -ne 1) { throw 'Could not resolve a unique current ODT download from Microsoft Download Center. Existing Office has not been removed.' } + $urls[0] +} + +function Invoke-OfficeProcess { + param([string]$FilePath, [string]$Arguments, [string]$LogPrefix) + $null = Write-Output "Running: $FilePath $Arguments. Process logs: $LogPrefix" + $process = Start-Process -FilePath $FilePath -ArgumentList $Arguments -WorkingDirectory (Split-Path -Parent $FilePath) -Wait -PassThru -WindowStyle Hidden -RedirectStandardOutput "$LogPrefix.stdout.log" -RedirectStandardError "$LogPrefix.stderr.log" -ErrorAction Stop + if ($null -eq $process.ExitCode) { throw "No exit code returned from $FilePath." } + $null = Write-Output "Process exited $($process.ExitCode): $FilePath" + [int]$process.ExitCode +} + +function New-OfficeConfiguration { + param($Options, [string]$SourcePath, [string]$Version) + $definitions = Get-OfficeDeploymentDefinitions + $xml = New-Object Xml.XmlDocument + $configuration = $xml.CreateElement('Configuration'); $null = $xml.AppendChild($configuration) + $add = $xml.CreateElement('Add') + $add.SetAttribute('OfficeClientEdition', $Options.OfficeArchitecture) + $add.SetAttribute('Channel', $Options.UpdateChannel); $add.SetAttribute('SourcePath', $SourcePath) + if ($Version) { $add.SetAttribute('Version', $Version) } + $product = $xml.CreateElement('Product'); $product.SetAttribute('ID', $Options.ProductId) + $language = $xml.CreateElement('Language'); $language.SetAttribute('ID', $definitions.Language); $null = $product.AppendChild($language) + # Deploy the modern companion apps explicitly for all users after Office. + foreach ($app in $definitions.OdtExcludedApps) { + $exclude = $xml.CreateElement('ExcludeApp'); $exclude.SetAttribute('ID', $app); $null = $product.AppendChild($exclude) + } + $null = $add.AppendChild($product); $null = $configuration.AppendChild($add) + $properties = @{ + SharedComputerLicensing = $(if ($Options.OfficeActivation -eq 'SharedComputer') { '1' } else { '0' }) + FORCEAPPSHUTDOWN = $(if ($Options.OfficeAppShutdown -eq 'Force') { 'TRUE' } else { 'FALSE' }) + DeviceBasedLicensing = '0'; SCLCacheOverride = '0' + } + foreach ($name in ($properties.Keys | Sort-Object)) { + $property = $xml.CreateElement('Property'); $property.SetAttribute('Name', $name); $property.SetAttribute('Value', $properties[$name]); $null = $configuration.AppendChild($property) + } + $updates = $xml.CreateElement('Updates'); $updates.SetAttribute('Enabled', 'TRUE'); $updates.SetAttribute('Channel', $Options.UpdateChannel); $null = $configuration.AppendChild($updates) + $null = $configuration.AppendChild($xml.CreateElement('RemoveMSI')) + $display = $xml.CreateElement('Display'); $display.SetAttribute('Level', 'None'); $display.SetAttribute('AcceptEULA', 'TRUE'); $null = $configuration.AppendChild($display) + if ($Options.Company) { + $settings = $xml.CreateElement('AppSettings'); $setup = $xml.CreateElement('Setup') + $setup.SetAttribute('Name', 'Company'); $setup.SetAttribute('Value', $Options.Company) + $null = $settings.AppendChild($setup); $null = $configuration.AppendChild($settings) + } + return ,$xml +} + +function Initialize-OfficeMedia { + param($Options, [string]$Workspace) + $definitions = Get-OfficeDeploymentDefinitions + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + $page = Invoke-WebRequest -UseBasicParsing -Uri $definitions.OdtPage -TimeoutSec $definitions.OdtPageTimeoutSeconds -ErrorAction Stop + $url = Get-OfficeOdtDownloadUrl $page.Content + $package = Join-Path $Workspace 'odt.exe' + $null = Write-Output "Downloading current ODT from $url" + Save-OfficeDownload $url $package + Assert-OfficeMicrosoftSignature $package + $odtFolder = Join-Path $Workspace 'ODT'; $null = New-Item -ItemType Directory -Path $odtFolder + $code = Invoke-OfficeProcess $package "/quiet /extract:`"$odtFolder`"" (Join-Path $Workspace 'odt-extract') + if ($code -ne 0) { throw "ODT extraction failed ($code)." } + $setup = Join-Path $odtFolder 'setup.exe'; Assert-OfficeMicrosoftSignature $setup + # Microsoft's evergreen Get Help link retains its historical SaRA name. + $scrubZip = Join-Path $Workspace 'GetHelp.zip' + Save-OfficeDownload $definitions.GetHelpUrl $scrubZip + $scrubFolder = Join-Path $Workspace 'GetHelp' + Expand-Archive -LiteralPath $scrubZip -DestinationPath $scrubFolder -ErrorAction Stop + $scrub = @(Get-ChildItem -LiteralPath $scrubFolder -Filter $definitions.GetHelpExecutable -File -Recurse) + if ($scrub.Count -ne 1) { throw "Microsoft download did not contain exactly one $($definitions.GetHelpExecutable)." } + Assert-OfficeMicrosoftSignature $scrub[0].FullName + # Run-Script only downloads the core file, so stage its helper explicitly. + $helper = Join-Path $Workspace 'Office-UserCleanup.ps1' + Save-OfficeDownload "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1" $helper + $tokens = $null; $errors = $null + $null = [Management.Automation.Language.Parser]::ParseFile($helper, [ref]$tokens, [ref]$errors) + if ($errors.Count -or !(Select-String -LiteralPath $helper -SimpleMatch $definitions.HelperVersion -Quiet)) { throw 'Office user cleanup helper is invalid; publish it with this installer.' } + $configPath = Join-Path $Workspace 'install.xml' + $config = New-OfficeConfiguration $Options $odtFolder; $config.Save($configPath) + $null = Write-Output 'Downloading Office installation files before removing installed apps.' + $code = Invoke-OfficeProcess $setup "/download `"$configPath`"" (Join-Path $Workspace 'office-download') + if ($code -ne 0) { throw "Office download failed ($code). Existing Office has not been removed." } + $versions = @(Get-ChildItem -LiteralPath (Join-Path $odtFolder 'Office\Data') -Directory -ErrorAction Stop | Where-Object { $_.Name -match $definitions.OfficeBuildPattern }) + if ($versions.Count -ne 1) { throw 'Office download did not produce one identifiable build.' } + $arch = if ($Options.OfficeArchitecture -eq '64') { 'x64' } else { 'x86' } + foreach ($stream in @("stream.$arch.x-none.dat", "stream.$arch.$($definitions.Language).dat")) { + if ((Get-Item -LiteralPath (Join-Path $versions[0].FullName $stream) -ErrorAction Stop).Length -eq 0) { throw "Office payload is empty: $stream" } + } + $config.Configuration.Add.SetAttribute('Version', $versions[0].Name); $config.Save($configPath) + $companions = Initialize-OfficeCompanionMedia $Workspace -InstallTeams $Options.InstallTeams + [pscustomobject]@{ Setup = $setup; Scrubber = $scrub[0].FullName; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions } +} + +function Get-OfficeRunningApps { + Get-Process -Name (Get-OfficeDeploymentDefinitions).RunningAppNames -ErrorAction SilentlyContinue +} + +function Stop-OfficeDeploymentApps { + param($Options) + $running = @(Get-OfficeRunningApps) + if (!$running.Count) { return } + if ($Options.OfficeAppShutdown -ne 'Force') { throw "Apps are running: $(($running.ProcessName | Sort-Object -Unique) -join ', '). Close them or select OfficeAppShutdown=Force (unsaved work can be lost)." } + $null = Write-Output 'Closing Office, Teams, OneDrive, and new Outlook in every session. Unsaved work can be lost.' + $running | Stop-Process -Force -ErrorAction Stop +} + +function Get-OfficeCompanionDownloads { + param([bool]$InstallTeams = $false) + $definitions = Get-OfficeDeploymentDefinitions + # Companion architecture follows Windows, even when 32-bit Office is selected. + $architecture = if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64' -or $env:PROCESSOR_ARCHITEW6432 -eq 'ARM64') { 'ARM64' } elseif ([Environment]::Is64BitOperatingSystem) { 'x64' } else { 'x86' } + foreach ($name in @('WebView2', 'Teams', 'NewOutlook', 'OneDrive')) { + if ($name -eq 'Teams' -and !$InstallTeams) { continue } + $installer = $definitions.CompanionInstallers[$name] + $uri = if ($name -eq 'OneDrive') { $installer.Uris[$architecture] } else { $installer.Uri } + [pscustomobject]@{ Name=$name; File=$installer.File; Uri=$uri } + } +} + +function Initialize-OfficeCompanionMedia { + param([string]$Workspace, [bool]$InstallTeams = $false) + $media = @{} + foreach ($download in (Get-OfficeCompanionDownloads -InstallTeams $InstallTeams)) { + $path = Join-Path $Workspace $download.File + $null = Write-Output "Staging the current Microsoft $($download.Name) installer." + Save-OfficeDownload $download.Uri $path + Assert-OfficeMicrosoftSignature $path + $media[$download.Name] = $path + } + # Teams, Outlook and WebView2 bootstrappers still need internet access at install time. + $media +} + +function Get-OfficeMachineWebViewVersion { + foreach ($root in @('HKLM:\SOFTWARE\WOW6432Node', 'HKLM:\SOFTWARE')) { + $value = Get-ItemPropertyValue -LiteralPath "$root\Microsoft\EdgeUpdate\Clients\$((Get-OfficeDeploymentDefinitions).WebViewClientId)" -Name pv -ErrorAction SilentlyContinue + if ($value -match '^\d+\.\d+\.\d+\.\d+$' -and [version]$value -gt [version]'0.0.0.0') { return [string]$value } + } +} + +function Get-OfficeMachineOneDrive { + $version = $null + foreach ($key in @('HKLM:\SOFTWARE\Microsoft\OneDrive', 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\OneDrive')) { + $value = Get-ItemPropertyValue -LiteralPath $key -Name Version -ErrorAction SilentlyContinue + if ($value -match '^\d+\.\d+\.\d+\.\d+$') { $version = [string]$value; break } + } + if (!$version) { return } + foreach ($folder in @($env:ProgramFiles, ${env:ProgramFiles(x86)})) { + if (!$folder) { continue } + $path = Join-Path $folder 'Microsoft OneDrive\OneDrive.exe' + if (Test-Path -LiteralPath $path -PathType Leaf) { return [pscustomobject]@{ Version=$version; Path=$path } } + } +} + +function Install-OfficeCompanionApps { + param([hashtable]$Media, [string]$Workspace, [bool]$InstallTeams = $false) + $definitions = Get-OfficeDeploymentDefinitions + $reboot = $false + $webViewVersion = Get-OfficeMachineWebViewVersion + if (!$webViewVersion) { + $code = Invoke-OfficeProcess $Media.WebView2 $definitions.CompanionInstallers.WebView2.Arguments (Join-Path $Workspace 'webview2-install') + if ($code -notin @(0, 3010)) { throw "WebView2 installation failed (exit $code)." } + if ($code -eq 3010) { $reboot = $true } + $webViewVersion = Get-OfficeMachineWebViewVersion + if (!$webViewVersion) { throw 'WebView2 setup returned success but no machine-wide runtime was detected.' } + } + $versions = [ordered]@{ WebView2=$webViewVersion } + if (!$InstallTeams) { $null = Write-Output 'Skipping Teams: the selected subscription does not include Teams.' } + foreach ($name in @('OneDrive', 'Teams', 'NewOutlook')) { + if ($name -eq 'Teams' -and !$InstallTeams) { continue } + $app = $definitions.CompanionInstallers[$name].Clone(); $app.Name = $name + $null = Write-Output "Installing $($app.Name) for all users." + # Start-Process passes these native executable arguments unchanged on Windows PowerShell 5.1. + $code = Invoke-OfficeProcess $Media[$app.Name] $app.Arguments (Join-Path $Workspace ($app.Name + '-install')) + if ($code -notin @(0, 3010)) { throw "$($app.Name) installation failed (exit $code). See logs in $Workspace." } + if ($code -eq 3010) { $reboot = $true } + if ($app.Package) { + $packages = @(Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.DisplayName -eq $app.Package -and $_.PackageName -like ('*' + $definitions.AppxPublisherSuffix) }) + if (!$packages.Count) { throw "$($app.Name) setup returned success but the app was not provisioned for all users." } + $versions[$app.Name] = ($packages.Version | Sort-Object -Unique) -join ', ' + } else { + $oneDrive = Get-OfficeMachineOneDrive + if (!$oneDrive) { throw 'OneDrive setup returned success but a per-machine installation was not detected.' } + Assert-OfficeMicrosoftSignature $oneDrive.Path + $versions.OneDrive = $oneDrive.Version + } + } + [pscustomobject]@{ ExitCode=$(if ($reboot) {3010} else {0}); Versions=[pscustomobject]$versions } +} + +function Set-OfficeReinstallPhase { + param([string]$Workspace) + # A read-only exclusive file handle works for both SYSTEM and limited users. + # Serialize this transition with user uninstallers so a late sign-in cannot undo installation. + if (!(Test-Path -LiteralPath (Join-Path $Workspace 'user-cleanup.lock') -PathType Leaf)) { throw 'User cleanup lock file is missing; cannot begin reinstallation.' } + $deadline = [DateTime]::UtcNow.AddMinutes((Get-OfficeDeploymentDefinitions).UserCleanupWaitMinutes); $lock = $null + do { + try { $lock = [IO.File]::Open((Join-Path $Workspace 'user-cleanup.lock'), [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None) } + catch [IO.IOException] { if ([DateTime]::UtcNow -ge $deadline) { throw 'User cleanup is still active; cannot begin reinstallation.' }; Start-Sleep -Seconds 2 } + } while ($null -eq $lock) + try { Set-Content -LiteralPath (Join-Path $Workspace 'reinstall-started') -Value 'Preserve newly installed companion apps.' -ErrorAction Stop } + finally { $lock.Dispose() } +} + +function Get-OfficeUninstallEntries { + foreach ($root in @('HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall')) { + if (Test-Path -LiteralPath $root) { Get-ItemProperty -Path "$root\*" -ErrorAction Stop | Where-Object { $_.DisplayName -and $_.Publisher -like 'Microsoft*' } } + } +} + +function Get-OfficeSuiteInventory { + # Avoid Win32_Product, which can trigger MSI repairs. + Get-OfficeUninstallEntries | Where-Object { + $_.DisplayName -match '(?i)^(Microsoft\s+)?(365|Office|Visio|Project|Access|Word|Excel|Outlook|PowerPoint|OneNote|Publisher|Skype for Business)(\s|$)' -and + $_.DisplayName -notmatch '(?i)(Add-in|Addin|Redistributable|Database Engine|Extensibility|Update|Hotfix|Click-to-Run)' + } + $c2r = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration' -ErrorAction SilentlyContinue + if ($c2r.ProductReleaseIds) { [pscustomobject]@{ DisplayName = "Click-to-Run: $($c2r.ProductReleaseIds)" } } +} + +function Assert-OfficeScrubResult { + param([int]$ExitCode, [string]$Output, [object[]]$RemainingOffice) + # Microsoft's scenario output is checked separately from the process exit code. + $definitions = Get-OfficeDeploymentDefinitions + $results = [regex]::Matches($Output, $definitions.ScrubScenarioPattern) + if (!$results.Count) { throw "Get Help returned no recognizable scenario result (process exit $ExitCode). Check scrub logs." } + $result = $results[$results.Count - 1].Groups[1].Value + if ($result -notin $definitions.ScrubScenarioSuccess -or $ExitCode -notin $definitions.ScrubExitSuccess) { throw "Get Help removal failed: scenario $result, process $ExitCode. Check scrub logs." } + if (@($RemainingOffice).Count) { throw "Office remains after cleanup: $(($RemainingOffice | ForEach-Object { $_.DisplayName }) -join '; '). Reboot/repair and rerun; installation stopped." } +} + +function Remove-OfficeSuite { + param($Media, [string]$Workspace) + $null = Write-Output 'Removing Office, including Visio and Project, with Microsoft Get Help.' + $prefix = Join-Path $Workspace 'office-scrub' + $code = Invoke-OfficeProcess $Media.Scrubber (Get-OfficeDeploymentDefinitions).ScrubArguments $prefix + $output = (Get-Content -LiteralPath "$prefix.stdout.log" -Raw -ErrorAction Stop) + (Get-Content -LiteralPath "$prefix.stderr.log" -Raw -ErrorAction Stop) + Assert-OfficeScrubResult $code $output @(Get-OfficeSuiteInventory) +} + +function Get-OfficeAppxNames { + (Get-OfficeDeploymentDefinitions).AppxRemovalNames +} + +function Get-OfficeOneDriveCommand { + param([string]$UninstallString, [string[]]$AllowedRoots) + $match = [regex]::Match($UninstallString, '^\s*"([^"\r\n]+\\OneDriveSetup\.exe)"\s+(/[^\r\n]*)$', 'IgnoreCase') + if (!$match.Success) { throw 'Unrecognized OneDrive uninstall command; refusing arbitrary uninstall text.' } + $exe = [IO.Path]::GetFullPath($match.Groups[1].Value) + $allowed = $false + foreach ($root in $AllowedRoots) { + if ($root -and $exe.StartsWith([IO.Path]::GetFullPath($root).TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase)) { $allowed = $true } + } + $arguments = $match.Groups[2].Value.Trim() + if (!$allowed -or $arguments -notmatch '(?i)^/(uninstall|allusers)(\s+/(uninstall|allusers))*$' -or $arguments -notmatch '(?i)/uninstall\b') { throw 'OneDrive uninstall path or arguments are outside the supported allowlist.' } + [pscustomobject]@{ FilePath = $exe; Arguments = $arguments } +} + +function Remove-OfficeCompanionApps { + param([string]$Workspace) + $names = Get-OfficeAppxNames + $definitions = Get-OfficeDeploymentDefinitions + foreach ($package in @(Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.DisplayName -in $names })) { + $null = Write-Output "Removing provisioned package: $($package.PackageName)" + $null = Remove-AppxProvisionedPackage -Online -PackageName $package.PackageName -AllUsers -ErrorAction Stop + } + foreach ($package in @(Get-AppxPackage -AllUsers -ErrorAction Stop | Where-Object { $_.Name -in $names })) { + $null = Write-Output "Removing installed package: $($package.PackageFullName)" + Remove-AppxPackage -Package $package.PackageFullName -AllUsers -ErrorAction Stop + } + if (@(Get-AppxPackage -AllUsers -ErrorAction Stop | Where-Object { $_.Name -in $names }).Count) { throw 'Office/Teams/Outlook Store packages remain after removal.' } + $reboot = $false + foreach ($entry in @(Get-OfficeUninstallEntries)) { + if ($entry.DisplayName -in $definitions.TeamsMsiNames) { + if ($entry.PSChildName -notmatch '^\{[0-9A-Fa-f-]{36}\}$') { throw 'Teams MSI has an unexpected product code.' } + $prefix = Join-Path $Workspace ('teams-' + $entry.PSChildName) + $code = Invoke-OfficeProcess "$env:WINDIR\System32\msiexec.exe" "/x $($entry.PSChildName) /qn /norestart /L*v `"$prefix.log`"" $prefix + } elseif ($entry.DisplayName -eq 'Microsoft OneDrive') { + $roots = @((Join-Path $env:ProgramFiles 'Microsoft OneDrive'), (Join-Path $env:WINDIR 'System32'), (Join-Path $env:WINDIR 'SysWOW64')) + if (${env:ProgramFiles(x86)}) { $roots += Join-Path ${env:ProgramFiles(x86)} 'Microsoft OneDrive' } + $command = Get-OfficeOneDriveCommand $entry.UninstallString $roots + Assert-OfficeMicrosoftSignature $command.FilePath + $code = Invoke-OfficeProcess $command.FilePath $command.Arguments (Join-Path $Workspace 'onedrive-machine') + } else { continue } + if ($code -eq 3010) { $reboot = $true } + elseif ($code -notin @(0, 1605, 1614)) { throw "Could not remove $($entry.DisplayName) (exit $code)." } + } + if (@(Get-OfficeUninstallEntries | Where-Object { $_.DisplayName -in (@('Microsoft OneDrive') + $definitions.TeamsMsiNames) }).Count -and !$reboot) { throw 'A machine-wide Teams/OneDrive installation remains after removal.' } + $reboot +} + +function Remove-OfficeProfileCache { + param([string]$ProfilePath) + $profileRoot = [IO.Path]::GetFullPath($ProfilePath).TrimEnd('\') + foreach ($relative in (Get-OfficeDeploymentDefinitions).OfficeCachePaths) { + $target = [IO.Path]::GetFullPath((Join-Path $profileRoot $relative)) + if (!$target.StartsWith($profileRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Office cache path escaped the profile.' } + if (!(Test-Path -LiteralPath $target)) { continue } + for ($item = Get-Item -LiteralPath $target -Force; $null -ne $item; $item = $item.Parent) { + if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Office cache traverses a reparse point: $($item.FullName)" } + } + if (@(Get-ChildItem -LiteralPath $target -Recurse -Force -ErrorAction Stop | Where-Object { $_.Attributes -band [IO.FileAttributes]::ReparsePoint }).Count) { throw "Office cache contains a reparse point: $target" } + $null = Write-Output "Removing Office licensing cache: $target" + Remove-Item -LiteralPath $target -Recurse -Force -ErrorAction Stop + } +} + +function Clear-OfficeProfileIdentity { + param($Profile) + $definitions = Get-OfficeDeploymentDefinitions + $null = Write-Output "Clearing Office identity/licensing for profile $($Profile.SID): $($Profile.LocalPath)" + Remove-OfficeProfileCache $Profile.LocalPath + $hive = "Registry::HKEY_USERS\$($Profile.SID)"; $mounted = $false + if (!(Test-Path -LiteralPath $hive)) { + $hiveName = 'EmberkomOffice_' + [guid]::NewGuid().ToString('N'); $hive = "Registry::HKEY_USERS\$hiveName" + & "$env:WINDIR\System32\reg.exe" load "HKU\$hiveName" (Join-Path $Profile.LocalPath 'NTUSER.DAT') | Out-Null + if ($LASTEXITCODE -ne 0) { throw "Could not load Office identity hive for $($Profile.SID)." } + $mounted = $true + } + try { + foreach ($version in $definitions.OfficeIdentityVersions) { + foreach ($key in $definitions.OfficeIdentityKeys) { + $target = "$hive\Software\Microsoft\Office\$version\Common\$key" + if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Recurse -Force -ErrorAction Stop } + } + } + } finally { + if ($mounted) { + [GC]::Collect(); [GC]::WaitForPendingFinalizers() + & "$env:WINDIR\System32\reg.exe" unload "HKU\$hiveName" | Out-Null + if ($LASTEXITCODE -ne 0) { throw "Could not unload temporary Office hive $hiveName." } + } + } +} + +function Start-OfficeUserCleanup { + param([object[]]$Profiles, $Media, [string]$Workspace) + $definitions = Get-OfficeDeploymentDefinitions + $deploymentId = Split-Path -Leaf $Workspace; $tasks = @() + foreach ($profile in $Profiles) { + $name = "Emberkom-OfficeCleanup-$deploymentId-$($profile.SID)" + $action = New-ScheduledTaskAction -Execute "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$($Media.Helper)`" -DeploymentId $deploymentId" + $principal = New-ScheduledTaskPrincipal -UserId $profile.SID -LogonType Interactive -RunLevel Limited + $trigger = New-ScheduledTaskTrigger -AtLogOn -User $profile.SID + $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes $definitions.UserCleanupTaskMinutes) -MultipleInstances IgnoreNew + $null = Write-Output "Registering user cleanup task: $name" + $null = Register-ScheduledTask -TaskName $name -Action $action -Principal $principal -Trigger $trigger -Settings $settings -Force -ErrorAction Stop + $tasks += [pscustomobject]@{ Name = $name; SID = $profile.SID; WasLoaded = $profile.Loaded } + if ($profile.Loaded) { + try { Start-ScheduledTask -TaskName $name -ErrorAction Stop } + catch { Write-Error "Cleanup for $($profile.SID) will retry at sign-in: $($_.Exception.Message)" -ErrorAction Continue } + } + } + $deadline = [DateTime]::UtcNow.AddMinutes($definitions.UserCleanupWaitMinutes) + do { + $waiting = @($tasks | Where-Object { $_.WasLoaded -and (Get-ScheduledTask -TaskName $_.Name -ErrorAction Stop).State -in @('Running', 'Queued') }) + if ($waiting.Count) { Start-Sleep -Seconds 2 } + } while ($waiting.Count -and [DateTime]::UtcNow -lt $deadline) + if ($waiting.Count) { throw 'User cleanup is still running. Installation stopped to avoid concurrent uninstall/install operations. Check scheduled task results.' } + $pending = @() + foreach ($task in $tasks) { + $marker = Get-ItemPropertyValue -LiteralPath "Registry::HKEY_USERS\$($task.SID)\Software\Emberkom\OfficeDeployment\$deploymentId" -Name Status -ErrorAction SilentlyContinue + if ($marker -eq 'Complete') { Unregister-ScheduledTask -TaskName $task.Name -Confirm:$false -ErrorAction Stop } + else { $pending += $task.SID; $null = Write-Output "Cleanup pending for $($task.SID); task $($task.Name) runs at their next sign-in." } + } + return ,$pending +} + +function Install-OfficeMedia { + param($Options, $Media, [string]$Workspace) + $code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.Config)`"" (Join-Path $Workspace 'office-install') + if ($code -notin @(0, 3010)) { throw "Office installation failed (exit $code). Media and logs remain in $Workspace." } + $installed = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration' -ErrorAction Stop + $platform = if ($Options.OfficeArchitecture -eq '64') { 'x64' } else { 'x86' } + if ($Options.ProductId -notin ($installed.ProductReleaseIds -split ',') -or $installed.Platform -ne $platform -or $installed.VersionToReport -ne $Media.Version) { throw 'Setup exited successfully but the installed product, architecture, or version did not match.' } + $code +} + +function Invoke-OfficeDeployment { + param($Options) + $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue' + # Internal action messages use Tools.ps1's logger. Suppress its echoed success output + # so it cannot become part of a function's return value. Entry prints the Syncro receipt. + if ($Options.ValidateBeforeChanges -isnot [bool]) { throw 'ValidateBeforeChanges must be a validated Boolean before running the workload.' } + Assert-OfficeDeploymentHost $Options + $mutex = New-Object Threading.Mutex($false, 'Global\EmberkomOfficeDeployment') + $locked = $false + try { + try { $locked = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $locked = $true } + if (!$locked) { throw 'Another Emberkom Office deployment is running.' } + $runningApps = @(Get-OfficeRunningApps | Select-Object -ExpandProperty ProcessName -Unique) + if ($runningApps.Count -and $Options.OfficeAppShutdown -eq 'Abort') { throw "Apps are running: $($runningApps -join ', '). Close them or select OfficeAppShutdown=Force for the maintenance window." } + $workspace = New-OfficeWorkspace + $null = Write-Output "Office request: $($Options.OfficeSubscription) / $($Options.ProductId), $($Options.OfficeArchitecture)-bit, $($Options.UpdateChannel), ValidateBeforeChanges=$($Options.ValidateBeforeChanges). Workspace: $workspace" + $Options | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $workspace 'options.json') -Encoding UTF8 + $profiles = @(Get-CimInstance Win32_UserProfile -ErrorAction Stop | Where-Object { !$_.Special -and $_.LocalPath }) + # Unavailable containers/roaming profiles must not silently disappear from the cleanup report. + foreach ($profile in $profiles) { + if (!(Test-Path -LiteralPath (Join-Path $profile.LocalPath 'NTUSER.DAT'))) { throw "Profile $($profile.SID) is unavailable. Mount its profile/container before deploying." } + } + $media = Initialize-OfficeMedia $Options $workspace + if ($Options.ValidateBeforeChanges) { + $existingOffice = @(Get-OfficeSuiteInventory | ForEach-Object { $_.DisplayName }) + $null = Write-Output 'Validation passed. Stopped before closing apps, uninstalling, clearing identities, registering tasks, or installing.' + return [pscustomobject]@{ + OfficeDeploymentStatus='ValidationPassed'; ExitCode=0; ValidateBeforeChanges=$true + ProductId=$Options.ProductId; OfficeVersion=$media.Version; Architecture=$Options.OfficeArchitecture + UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams + Workspace=$workspace; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps + NextStep='Set ValidateBeforeChanges=false to deploy. That run repeats validation and downloads fresh media.' + } + } + Stop-OfficeDeploymentApps $Options + $reboot = Remove-OfficeCompanionApps $workspace + if ($reboot) { + $null = Write-Output 'Companion app removal requires a restart. Restart and rerun; Office installation has not started.' + return [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; Workspace = $workspace; PendingUserSids = @() } + } + Remove-OfficeSuite $media $workspace + foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile } + $pending = Start-OfficeUserCleanup $profiles $media $workspace + Set-OfficeReinstallPhase $workspace + $code = Install-OfficeMedia $Options $media $workspace + $companions = Install-OfficeCompanionApps $media.Companions $workspace -InstallTeams $Options.InstallTeams + if ($companions.ExitCode -eq 3010) { $code = 3010 } + $status = if ($pending.Count) { 'InstalledWithUserCleanupPending' } else { 'Installed' } + $null = Write-Output "$status. Office $($media.Version), $($Options.ProductId). Restart after the Office scrub is recommended; no automatic reboot was requested." + $provisionedApps = if ($Options.InstallTeams) { 'Teams and new Outlook are' } else { 'New Outlook is' } + $null = Write-Output "$provisionedApps provisioned for all users; OneDrive is installed per-machine. Users may need to sign out and back in to register the apps." + $null = Write-Output 'Windows work-account/WAM sign-in is preserved; Windows SSO can sign Office in again. App installation does not grant Teams or mailbox entitlements.' + [pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if ($pending.Count -and $code -eq 0) { 2 } else { $code }); ValidateBeforeChanges=$false; Workspace = $workspace; PendingUserSids = $pending; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version } + } finally { + if ($locked) { $mutex.ReleaseMutex() } + $mutex.Dispose() + } +} + +function New-OfficeNativeCommand { + param([hashtable]$InputValues) + # Reload Tools in the child, preserving the caller's diagnostic log and injected strings. + $context = @{ Inputs=$InputValues; LogFile=[string]$Global:LogFile; RepositoryRoot=(Get-OfficeDeploymentDefinitions).RepositoryRoot } + $json64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($context | ConvertTo-Json -Depth 4 -Compress))) + $command = @' +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$officeContext = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__INPUTS__')) | ConvertFrom-Json +$client = New-Object Net.WebClient +try { + . ([scriptblock]::Create($client.DownloadString($officeContext.RepositoryRoot + '/Tools.ps1'))) + if ($officeContext.LogFile) { $Global:LogFile = $officeContext.LogFile } + foreach ($property in $officeContext.Inputs.PSObject.Properties) { Set-Variable -Name $property.Name -Value $property.Value } + $source = $client.DownloadString($officeContext.RepositoryRoot + '/Install-MicrosoftOffice365.ps1') + . ([scriptblock]::Create($source)) + throw 'Office workload returned without reporting an exit code.' +} catch { + $message = "Office bootstrap failed: $($_.Exception.Message)" + try { Write-Error $message -ErrorAction Continue } + finally { Microsoft.PowerShell.Utility\Write-Output "ERROR: $message"; exit 1 } +} +finally { $client.Dispose() } +'@ + $command.Replace('__INPUTS__', $json64) +} + +function Invoke-OfficeDeploymentEntry { + param([hashtable]$InputValues, [Parameter(Mandatory=$true)][ref]$ExitCode) + $ErrorActionPreference = 'Stop' + $ExitCode.Value = 1 + $options = Get-OfficeDeploymentOptions $InputValues + if (([Environment]::Is64BitOperatingSystem -and ![Environment]::Is64BitProcess) -or $PSVersionTable.PSEdition -eq 'Core') { + $command = New-OfficeNativeCommand $InputValues + # Keep child host/warning messages readable in Syncro instead of emitting CLIXML on stderr. + $command = '$ProgressPreference = ''SilentlyContinue''; & {' + [Environment]::NewLine + $command + [Environment]::NewLine + '} 2>&1 3>&1 4>&1 5>&1 6>&1' + $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command)) + $nativeFolder = if ([Environment]::Is64BitOperatingSystem -and ![Environment]::Is64BitProcess) { 'Sysnative' } else { 'System32' } + $native = Join-Path $env:WINDIR "$nativeFolder\WindowsPowerShell\v1.0\powershell.exe" + & $native -NoProfile -NonInteractive -ExecutionPolicy Bypass -OutputFormat Text -EncodedCommand $encoded | ForEach-Object { Microsoft.PowerShell.Utility\Write-Output $_ } + $ExitCode.Value = [int]$LASTEXITCODE + if ($ExitCode.Value -eq 1) { Write-Error "Office native-host run failed. See the Syncro output and log: $Global:LogFile" -ErrorAction Continue } + return + } + $null = Write-Output "Office deployment host: Windows PowerShell $($PSVersionTable.PSVersion), $([IntPtr]::Size * 8)-bit." + if ($options.ValidateBeforeChanges) { + Microsoft.PowerShell.Utility\Write-Output 'Validation only: checking prerequisites and staging current installers/Office media (several GB). No app shutdown, cleanup, or installation will run.' + } else { + Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: validating and staging media, then removing and reinstalling Office and the selected companion apps.' + } + Microsoft.PowerShell.Utility\Write-Output "Diagnostic log: $Global:LogFile" + $results = @(Invoke-OfficeDeployment -Options $options) + $deployment = @($results | Where-Object { $_.PSObject.Properties['OfficeDeploymentStatus'] }) + $results | Where-Object { !($_.PSObject.Properties['OfficeDeploymentStatus']) } | ForEach-Object { $null = Write-Output ([string]$_) } + if ($deployment.Count -ne 1) { throw 'Office deployment did not return a verified result.' } + $receipt = $deployment[0] | ConvertTo-Json -Depth 4 + $null = Write-Output $receipt + Microsoft.PowerShell.Utility\Write-Output $receipt + if ($deployment[0].OfficeDeploymentStatus -like 'Installed*') { + Microsoft.PowerShell.Utility\Write-Output 'Restart after the Office scrub is recommended. Users may need to sign out and back in for companion app registration; check PendingUserSids for deferred cleanup.' + } + $ExitCode.Value = [int]$deployment[0].ExitCode +} + +$OfficeInputValues = @{} +foreach ($OfficeInputName in @('OfficeSubscription', 'OfficeArchitecture', 'UpdateChannel', 'OfficeActivation', 'OfficeAppShutdown', 'ValidateBeforeChanges', 'COMPANY')) { + $OfficeInputVariable = Get-Variable -Name $OfficeInputName -ErrorAction SilentlyContinue + $OfficeInputValues[$OfficeInputName] = if ($null -ne $OfficeInputVariable) { [string]$OfficeInputVariable.Value } else { '' } +} +try { + $OfficeExitCode = 1 + Invoke-OfficeDeploymentEntry -InputValues $OfficeInputValues -ExitCode ([ref]$OfficeExitCode) + exit $OfficeExitCode +} catch { + $OfficeFailureMessage = "Office deployment failed: $($_.Exception.Message)" + try { + $null = Write-Output "Failure location: $($_.ScriptStackTrace)" + Write-Error $OfficeFailureMessage -ErrorAction Continue + } finally { + Microsoft.PowerShell.Utility\Write-Output "ERROR: $OfficeFailureMessage" + Microsoft.PowerShell.Utility\Write-Output "Diagnostic log: $Global:LogFile" + exit 1 + } +} diff --git a/README.md b/README.md index e0ce4fa..4d30a56 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,10 @@ For download failures, use the standalone [Test-FileDownload.ps1](Test-FileDownl `Get-DSAManifest.ps1` uses `Download-FileDirectly`, which passes the original URL to BITS without preliminary `Get-AbsoluteURI` or `IsURLValid` requests. It accepts the same URL and optional `-File` arguments as `Download-File`, waits for completion, and throws on BITS errors. If `-File` is omitted, its temporary filename comes from the original URL; supply `-File` for extensionless URLs or URLs with query strings. Existing `Download-File` callers retain their previous behavior. Publish `Tools.ps1` together with `Get-DSAManifest.ps1` so the new helper is available. +## Microsoft 365 deployment + +See [Office365-Deployment.md](docs/Office365-Deployment.md) for the Syncro dropdowns and clean deployment workflow. Upload the shim in `rmm/Install-MicrosoftOffice365.ps1`; publish the core installer and `resources/office/Office-UserCleanup.ps1` together first. The shim uses the existing `Tools.ps1` unchanged; deployment, host relaunch, and result handling live in the main repository script. `ValidateBeforeChanges` defaults to `true` (checks and stages media only); explicitly select `false` to enable deployment. The workload runs in Windows PowerShell 5.1, requires an explicit subscription selection, removes Office and its companion apps, preserves Windows work-account sign-in, and installs the matching suite silently using Microsoft's current ODT. It then installs new Outlook and per-machine OneDrive using Microsoft's signed installers, plus current Teams only when the selected subscription includes Teams. Pending per-user cleanup is reported separately and protects the reinstalled apps. Action/error diagnostics use the existing Tools log; the result is printed to Syncro. + ## Converting RMM boolean variables After dot-sourcing `Tools.ps1`, use `ConvertTo-RmmBoolean` with any RMM variable: diff --git a/docs/Office365-Deployment.md b/docs/Office365-Deployment.md new file mode 100644 index 0000000..32bee22 --- /dev/null +++ b/docs/Office365-Deployment.md @@ -0,0 +1,124 @@ +# Microsoft 365 clean deployment through Syncro + +The script defaults to **validation only**. Set `ValidateBeforeChanges=false` explicitly to enable a destructive replacement of the Office installation. Deployment removes the Office suite, Visio, Project, separate Teams installations, OneDrive, and new Outlook, then silently installs the selected Microsoft 365 desktop suite, **new Outlook and OneDrive**, plus **current Teams only when the selected subscription includes Teams**. Classic Outlook is included alongside new Outlook. Visio and Project are not reinstalled. User documents, Outlook PST/OST files, and OneDrive sync folders are not deliberately deleted. Per-user cleanup for absent users has the boundaries described below. + +The selection identifies the client's purchased subscription; it does not discover tenant licenses, purchase a license, or assign one. The user still needs a matching assigned license. Windows work-account sign-in is preserved, so Windows SSO can sign Office in again. + +## Publish and configure + +1. Publish `Install-MicrosoftOffice365.ps1` and `resources/office/Office-UserCleanup.ps1` together in the public repository. The installer requires helper version `EmberkomOfficeUserCleanup-v2`, which protects reinstalled apps from deferred cleanup. The existing `Tools.ps1` is used unchanged. Nothing in this change publishes itself. +2. Paste/upload **rmm/Install-MicrosoftOffice365.ps1** as the Syncro **Windows PowerShell 5.1** script. Select **Run As: System**. PowerShell 7 is not required or launched. Allow a generous maximum runtime, initially 180 minutes, and enough disk space for both the download and installation. A clean deployment downloads several GB per endpoint and requires internet access throughout companion app installation. +3. Use **Add Script Variable**, type **Dropdown**, then **Edit Dropdown Values** for each variable below. Enter names without `$`. Syncro stores dropdown definitions separately; uploading a `.ps1` does not create them. See [Syncro's script editor documentation](https://docs.syncrosecure.com/scripting-apis/manage-scripts). +4. First run with `ValidateBeforeChanges=true` and review the result. To deploy, rerun with `false` during the maintenance window. Pilot on a disposable VM with representative Office, user profiles, and companion apps. Then run against the intended endpoint or asset selection. Group endpoints by subscription and architecture so each run's selections apply correctly. + +| Variable | Exact dropdown values | Default | +| --- | --- | --- | +| `ValidateBeforeChanges` | `true`, `false` | `true` (validate only; `false` enables removal/reinstallation) | +| `OfficeSubscription` | Use the subscription list below, plus `Select a subscription` | `Select a subscription` (deliberately rejected until changed) | +| `OfficeArchitecture` | `Auto`, `64`, `32` | `Auto` | +| `UpdateChannel` | `Current`, `MonthlyEnterprise`, `SemiAnnual` | `Current` | +| `OfficeActivation` | `User`, `SharedComputer` | `User` | +| `OfficeAppShutdown` | `Abort`, `Force` | `Abort` | + +All variables configured in Syncro must have a nonempty value. Set the dropdown defaults above in Syncro; the shim reads the injected strings without assigning over them. `Select a subscription` is a nonempty placeholder that the main script rejects before deployment. + +`ValidateBeforeChanges` uses the existing `ConvertTo-RmmBoolean` helper from `Tools.ps1`. Missing, null, or blank input defaults to `true`; invalid text fails. The workload requires a parsed Boolean, preventing an omitted or unparsed value from enabling changes. `false` still performs prerequisite and download validation before cleanup. It does not skip those checks. + +Syncro supplies `COMPANY` automatically with the endpoint's company name in this environment. Preserve that existing mapping; no company dropdown is needed. The shim passes it through to the main script, which includes `` in the ODT configuration, retaining the original installer's company setting. Outside Syncro, a missing value (or `None`) omits this setting. No product key, password, or tenant credentials are needed in Syncro. + +`Abort` stops if an Office app, Teams, OneDrive, or new Outlook is running. `Force` closes them across all sessions after staging succeeds; unsaved work can be lost. Choose Force only for the intended maintenance window. Deferred cleanup also closes that user's classic Teams when removing it at sign-in. + +`Auto` selects 64-bit Office on 64-bit Windows and 32-bit otherwise. Select `32` only for required add-in compatibility on supported x86/x64 systems. ARM64 rejects 32-bit Office. Companion installers follow the Windows architecture independently of Office bitness. The main repository script relaunches a 32-bit Syncro host into native Windows PowerShell 5.1 via `Sysnative` on 64-bit Windows, preserving the injected strings. All scheduled user cleanup also uses `powershell.exe`. The RMM shim contains no deployment or relaunch logic. + +Before removal, the script checks the apps' minimum OS requirements: Windows build 19041 or newer; Windows Server requires at least 2022 build 20348.2402 for new Outlook. Windows 10 LTSC is rejected when Teams is selected. These checks do not replace checking current Office/Windows support and the additional requirements of an RDS/AVD deployment. + +## Subscription choices + +Copy these exact names into the `OfficeSubscription` dropdown. The mapping follows [Microsoft's ODT product ID table](https://learn.microsoft.com/en-us/previous-versions/troubleshoot/microsoft-365/microsoft-365-apps/office-suite-problems/product-ids-supported-office-deployment-click-to-run). + +| Subscription | ODT product | +| --- | --- | +| Microsoft 365 Business Standard | O365BusinessRetail | +| Microsoft 365 Business Premium | O365BusinessRetail | +| Microsoft 365 Apps for business | O365BusinessEEANoTeamsRetail | +| Microsoft 365 Business Standard (no Teams) | O365BusinessEEANoTeamsRetail | +| Microsoft 365 Business Premium (no Teams) | O365BusinessEEANoTeamsRetail | +| Microsoft 365 Apps for enterprise | O365ProPlusEEANoTeamsRetail | +| Microsoft/Office 365 E3/E5 | O365ProPlusRetail | +| Microsoft/Office 365 E3/E5 (no Teams) | O365ProPlusEEANoTeamsRetail | + +The E3/E5 selections are consolidated because those plans use the same Office product and shared-computer activation validation. Their other subscription features do not change this installer. The previously documented individual E3/E5 names remain accepted as aliases for saved selections, but only the two combined names are needed in the dropdown. Business Standard and Premium remain separate because their shared-computer activation eligibility differs. + +All selections install new Outlook and OneDrive. Teams is downloaded and installed only for `Microsoft 365 Business Standard`, `Microsoft 365 Business Premium`, and `Microsoft/Office 365 E3/E5` (including their accepted legacy enterprise aliases). Every `(no Teams)` selection and both standalone `Microsoft 365 Apps for business` / `Microsoft 365 Apps for enterprise` selections skip the Teams download, installation, and installed-version verification. ODT also explicitly excludes Teams, so it cannot bypass this selection. Existing Teams installations are still removed during cleanup. Installing a client does not purchase/assign service entitlements; users must have the appropriate account and services to use it. + +Business Basic, E1, frontline/web-only plans, education/government variants, consumer subscriptions, and perpetual Office/LTSC editions are not deployment selections in this script. Missing or unsupported selections stop before downloads or removal. Existing perpetual Office installations can be removed by the scrubber; that does not authorize installing Microsoft 365 without its license. + +`SharedComputer` enables shared computer activation. Business Standard and standalone Apps for business are rejected for this mode; Business Premium and the listed eligible enterprise plans are accepted. Confirm the users' entitlements and host support, especially on RDS/AVD. See [Microsoft's shared activation requirements](https://learn.microsoft.com/en-us/microsoft-365-apps/licensing-activation/overview-shared-computer-activation). + +## Download, removal, and installation + +With `ValidateBeforeChanges=true`, the script checks the subscription/activation combination, host and OS prerequisites, running apps, and availability of registered user profiles. It downloads and verifies ODT, Get Help, the user cleanup helper, the full Office payload, and the selected companion bootstrappers. It writes the XML/options and returns `ValidationPassed` with the selected product, version, company, Teams choice, existing Office inventory, and running apps. It does **not** close apps, uninstall, clear identity/credentials, load user hives, register cleanup tasks, or install apps. `OfficeAppShutdown=Force` only reports running apps in this mode; `Abort` fails validation if any are running. + +Validation writes logs and staging files, secures its workspace, and runs ODT extraction and `/download`; it is not a zero-write inventory scan. Allow several GB and the same download time as deployment. A later `false` run downloads fresh media and repeats the checks. Validation does not prove tenant entitlements, successful future uninstallation/activation, or availability of the online companion payloads at install time. + +The script resolves the current versioned ODT download from the [Microsoft Download Center](https://www.microsoft.com/en-us/download/details.aspx?id=49117). It does not depend on the Emberkom-hosted setup.exe or a frozen Microsoft binary URL. If the page format changes, it stops before removal. The downloaded ODT package and extracted setup.exe must have valid Microsoft signatures. + +The [Get Help command-line package](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-command-line-overview) is downloaded fresh and its executable signature checked. Microsoft's evergreen link still uses the historical name `https://aka.ms/SaRA_EnterpriseVersionFiles`. The script executes `GetHelpCmd.exe`, not retired `SaRAcmd.exe`. + +ODT downloads the current build in the selected channel first. Installation is pinned to that local build, uses English (`en-us`), enables updates, and uses `Display Level="None"`. The [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options) describes these settings. Existing update policies can subsequently override the chosen channel. + +The companion apps remain excluded from ODT because the main script installs the selected companions explicitly for all users after Office. Their installers are downloaded from Microsoft's evergreen links and their Microsoft Authenticode signatures checked before any removal; Teams is staged only when the subscription includes it. Teams, new Outlook, and WebView2 use online bootstrappers: only their installer executables are staged, and their payload downloads can still fail later. The complete Office suite payload is staged before removal. + +| Component | Silent deployment | Verification | +| --- | --- | --- | +| WebView2 runtime, if missing machine-wide | `MicrosoftEdgeWebview2Setup.exe /silent /install` | Machine runtime version registration | +| OneDrive | `OneDriveSetup.exe /allusers /silent` | Machine version registration and Microsoft-signed executable under Program Files | +| Teams, when included in the subscription | `teamsbootstrapper.exe -p` | `MSTeams` provisioned package | +| New Outlook | `OutlookSetup.exe --provision true --quiet --start-` | `Microsoft.OutlookForWindows` provisioned package | + +These follow Microsoft's deployment guidance for [Teams](https://learn.microsoft.com/en-us/microsoftteams/teams-client-bulk-install), [new Outlook](https://learn.microsoft.com/en-us/microsoft-365-apps/outlook/get-started/deployment-new-outlook), [OneDrive per-machine installation](https://learn.microsoft.com/en-us/sharepoint/per-machine-installation), and [WebView2](https://learn.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution). Although the Outlook instructions show a PowerShell 7 shell, the command invokes a native executable; this script passes its arguments through `Start-Process` in Windows PowerShell 5.1. No `pwsh`, winget, or interactive Store sign-in is used. The existing evergreen WebView2 runtime, when present, retains its normal update mechanism. + +New Outlook, and Teams when selected, are provisioned for current and future users; users may need to sign out and back in for registration. OneDrive installs per-machine and handles migration of existing user accounts. App account setup and any tenant policy prompts are separate from the silent installation. The script does not switch the default mail application, force migration from classic Outlook, or configure OneDrive folder backup. + +Removal uses [Get Help's OfficeScrubScenario](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall) with `-OfficeVersion All`, plus separate targeted Appx/provisioned-package and Teams/OneDrive uninstall operations. Office 2007 through Microsoft 365/2024 are covered by the documented scrubber options. Corrupt, unsupported, orphaned, or unusually packaged installations may require manual repair; unknown uninstall commands and remaining detected Office products stop the deployment. This is not a guarantee that every historical Office artifact is erased. No automatic reboot or resume task is created. + +## Identity cleanup and absent users + +The core script clears Office 15/16 identity/licensing registry keys and Office licensing token folders in each locally available non-special Windows profile, loading unloaded user hives when needed. Unavailable profiles/containers stop deployment before removal. FSLogix/roaming profiles that are not registered locally are outside this script's coverage. + +Credential Manager belongs to each user. A limited-privilege scheduled task clears Office-prefixed credentials and removes per-user classic Teams. Before reinstallation begins, it also removes the user's old Teams meeting add-in and OneDrive. It runs immediately where a user session is available; otherwise it runs at that user's next sign-in. No passwords are stored. These tasks are named `Emberkom-OfficeCleanup--`. + +A file lock serializes user uninstallers with the transition to reinstallation. Once the protected `reinstall-started` marker is written, later user tasks preserve the Teams meeting add-in and OneDrive so they cannot uninstall the newly deployed apps. For absent users, OneDrive's per-machine installer handles migration; an existing per-user Teams meeting add-in can remain even when the Teams client is not reinstalled. Cleanup completion does not mean that every old per-user companion artifact was purged. Office credentials and classic Teams are still cleaned on the next sign-in. + +Windows work/school registration, WAM/AAD BrokerPlugin, generic Windows credentials, and device enrollment are preserved. This intentionally does not remove every Microsoft sign-in token. Microsoft's [activation reset guide](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365-apps/activation/reset-activation-state) distinguishes Office caches from shared WAM and workplace registration state. + +A deployment is reported as **InstalledWithUserCleanupPending** if any user task has not completed. Failed tasks also remain pending and retry on later sign-ins. The helper writes `Status=Complete` under `HKCU\Software\Emberkom\OfficeDeployment\` after success and then becomes a no-op. Tasks completed during deployment are removed automatically. Tasks that finish later remain registered; an administrator can confirm their marker/task result and unregister those exact tasks afterward. Do not delete their helper while any cleanup is pending. + +## Results and troubleshooting + +| Caller exit code | Meaning | +| --- | --- | +| `0` | `ValidationPassed`: validation only, no deployment performed. `Installed`: Office and companion installations verified; user cleanup completed for the enumerated profiles. | +| `1` | Failure; inspect the error and logs. In deployment mode, removal may already have happened. | +| `2` | Office and companion apps installed, but user cleanup is pending. Sign in as the listed users and inspect task results; do not repeatedly reinstall merely to check status. | +| `3010` | Restart required by an installer. Read `OfficeDeploymentStatus`: `RestartRequiredBeforeInstall` means restart then rerun; `Installed` or `InstalledWithUserCleanupPending` means Office and companions completed and an installer requested restart. Pending user SIDs can also be present. | + +Syncro may flag nonzero results as errors; read the printed status and pending SIDs. Get Help recommends a restart after a successful scrub even when the installer does not return 3010. Schedule that restart separately. + +The main script uses the overridden `Write-Output` and `Write-Error` from `Tools.ps1` for actions, retries, failures, and the final receipt, writing to its existing `$Global:LogFile`. Internal action messages suppress the logger's echoed success output to keep function results separate from diagnostics. The mode notice, log location, and final receipt use `Microsoft.PowerShell.Utility\Write-Output` for Syncro. Errors are logged and also printed to Syncro. Native PowerShell relaunch reloads Tools and restores the caller's log path. Run the core through the shim/Tools execution context, not as an independent file without Tools. + +Process stdout/stderr logs, options, generated XML, and downloaded media remain in `%ProgramData%\EmberkomOfficeDeployment\`. The main script records this folder in the Tools log and receipt. The separate limited-user cleanup task does not share the elevated Tools execution context; its transcript remains in `%LOCALAPPDATA%\Emberkom\OfficeDeployment\.log` for each user. Retained media can consume several GB per attempt. A validation-only folder can be removed after reviewing its results; for deployment folders, first remove all associated scheduled tasks. ODT/Get Help may also write diagnostic logs to the executing account's temp directory. + +The installer verifies the selected Office product, bitness, and downloaded version in Click-to-Run registration, plus selected companion deployment as listed above. The final receipt includes `CompanionApps` versions and `TeamsSelected`; when Teams is skipped, it has no installed version in that receipt. Any selected companion installer or verification failure fails the deployment, even if Office installed successfully. It does not claim that the subscription has activated. It does not delete mail profiles, revoke cloud sessions, or roll back a removed Office installation. + +## Verification + +Run `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\Install-MicrosoftOffice365.Tests.ps1` for offline checks. They require Windows PowerShell 5.1 and exercise the default validation gate (including `Force`), explicit deployment opt-out, log/console routing with the real Tools helpers, XML, removal-result handling, bounded cache deletion, companion installer failures/verification, deferred cleanup protection, and the unchanged `Run-Script` receiving injected strings through the shim with a mocked workload. An inert executable checks actual native argument passing; a 32-bit Windows PowerShell child checks relaunch into 64-bit Windows PowerShell 5.1 and exit-code propagation. They do not run Microsoft installers or clear actual credentials. + +`Run-Script` is unchanged. Its existing local execution can read the Syncro variables from the enclosing caller scope. The Office workload validates those values and reports its own result and exit code. The shim only sets TLS, dot-sources `Tools.ps1`, and invokes the workload. Existing `Run-Script` bootstrap failure behavior also remains unchanged. + +Endpoint acceptance still requires a VM pilot: existing MSI/C2R/Store Office, machine/per-user Teams and OneDrive, a logged-off profile, standard-user sign-in, wrong-license rejection, download failure, and the restart path. Verify new Outlook and Teams registration at sign-in, OneDrive migration, and that delayed cleanup preserves reinstalled apps. The implementation has not been run destructively against a real endpoint during development. + +## Maintaining deployment definitions + +`Get-OfficeDeploymentDefinitions` at the top of the main script groups subscription/product mappings, Teams and shared activation eligibility, allowed dropdown choices, download URLs/discovery patterns, installer arguments and package identities, language/build checks, OS minimums, cleanup targets, and timeouts. There is no additional configuration file. Review these contracts when Microsoft changes licensing, packaging, platform support, or cleanup behavior; evergreen downloads avoid routine version-number updates. Keep the Syncro dropdown definitions and this guide aligned when changing allowed selections. The limited-user helper retains its own scoped cleanup logic and version marker; changes to that contract require publishing both scripts together. diff --git a/resources/office/Office-UserCleanup.ps1 b/resources/office/Office-UserCleanup.ps1 new file mode 100644 index 0000000..b3a1808 --- /dev/null +++ b/resources/office/Office-UserCleanup.ps1 @@ -0,0 +1,140 @@ +#Requires -Version 5.1 +# EmberkomOfficeUserCleanup-v2 +# Run only as the affected user, at limited privilege; staged by the Office installer. +param([Parameter(Mandatory = $true)][ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId) + +function Test-OfficeCredentialTarget { + param([string]$Target) + # Preserve generic Azure AD, WindowsLive, OneDrive and MicrosoftAccount credentials. + $Target -match '^MicrosoftOffice(15|16)(?:_Data:|:)' +} + +function Clear-OfficeUserCredentials { + if (!('Emberkom.OfficeCredentials' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +namespace Emberkom { + public static class OfficeCredentials { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct Credential { + public UInt32 Flags, Type; + public string TargetName, Comment; + public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten; + public UInt32 CredentialBlobSize; + public IntPtr CredentialBlob; + public UInt32 Persist, AttributeCount; + public IntPtr Attributes; + public string TargetAlias, UserName; + } + [DllImport("advapi32.dll", EntryPoint="CredEnumerateW", CharSet=CharSet.Unicode, SetLastError=true)] + public static extern bool Enumerate(string filter, int flags, out int count, out IntPtr credentials); + [DllImport("advapi32.dll", EntryPoint="CredDeleteW", CharSet=CharSet.Unicode, SetLastError=true)] + public static extern bool Delete(string target, UInt32 type, int flags); + [DllImport("advapi32.dll")] public static extern void CredFree(IntPtr buffer); + } +} +'@ + } + $count = 0; $pointer = [IntPtr]::Zero + if (![Emberkom.OfficeCredentials]::Enumerate($null, 0, [ref]$count, [ref]$pointer)) { + $errorCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error() + if ($errorCode -eq 1168) { return } + throw "Cannot enumerate user credentials (Win32 $errorCode)." + } + try { + for ($index = 0; $index -lt $count; $index++) { + $entry = [Runtime.InteropServices.Marshal]::ReadIntPtr($pointer, $index * [IntPtr]::Size) + $credential = [Runtime.InteropServices.Marshal]::PtrToStructure($entry, [type][Emberkom.OfficeCredentials+Credential]) + if (Test-OfficeCredentialTarget $credential.TargetName) { + if (![Emberkom.OfficeCredentials]::Delete($credential.TargetName, $credential.Type, 0)) { throw 'Could not remove an Office credential.' } + } + } + } finally { [Emberkom.OfficeCredentials]::CredFree($pointer) } +} + +function Invoke-OfficeUserUninstaller { + param([string]$Path, [string]$Arguments) + $signature = Get-AuthenticodeSignature -LiteralPath $Path -ErrorAction Stop + if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch '(^|,\s*)O=Microsoft Corporation(,|$)') { throw "Uninstaller is not validly signed by Microsoft: $Path" } + $process = Start-Process -FilePath $Path -ArgumentList $Arguments -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop + if ($process.ExitCode -ne 0) { throw "User app uninstall failed ($($process.ExitCode)): $Path" } +} + +function Remove-OfficeUserLegacyTeams { + $teamsRoot = Join-Path $env:LOCALAPPDATA 'Microsoft\Teams' + $teamsUpdater = Join-Path $teamsRoot 'Update.exe' + if (Test-Path -LiteralPath $teamsUpdater) { + Get-Process -Name Teams -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq [Diagnostics.Process]::GetCurrentProcess().SessionId } | Stop-Process -Force -ErrorAction Stop + Invoke-OfficeUserUninstaller $teamsUpdater '--uninstall -s' + } + $teamsKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\Teams' + if ((Test-Path -LiteralPath (Join-Path $teamsRoot 'current\Teams.exe')) -or (Test-Path -LiteralPath $teamsKey)) { throw 'Classic Teams remains registered or installed for this user.' } +} + +function Remove-OfficeUserCompanions { + param([switch]$PreserveReinstalledApps) + Remove-OfficeUserLegacyTeams + if ($PreserveReinstalledApps) { + Write-Host 'Reinstallation has started. Preserving the Teams meeting add-in and leaving per-user OneDrive migration to the per-machine OneDrive installer.' + return + } + $uninstallRoot = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall' + if (Test-Path -LiteralPath $uninstallRoot) { + foreach ($entry in @(Get-ItemProperty -Path "$uninstallRoot\*" -ErrorAction Stop | Where-Object { $_.DisplayName -eq 'Microsoft Teams Meeting Add-in for Microsoft Office' -and $_.Publisher -like 'Microsoft*' })) { + if ($entry.PSChildName -notmatch '^\{[0-9A-Fa-f-]{36}\}$') { throw 'Unexpected per-user Teams add-in product code.' } + $process = Start-Process -FilePath "$env:WINDIR\System32\msiexec.exe" -ArgumentList "/x $($entry.PSChildName) /qn /norestart" -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop + if ($process.ExitCode -notin @(0, 1605, 1614)) { throw "Per-user Teams add-in removal needs attention (exit $($process.ExitCode))." } + if (Test-Path -LiteralPath $entry.PSPath) { throw 'Per-user Teams meeting add-in remains registered.' } + } + } + $oneDriveKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\OneDriveSetup.exe' + if (Test-Path -LiteralPath $oneDriveKey) { + $uninstall = (Get-ItemProperty -LiteralPath $oneDriveKey -ErrorAction Stop).UninstallString + $match = [regex]::Match($uninstall, '^\s*"([^"\r\n]+\\OneDriveSetup\.exe)"\s+/uninstall\s*$', 'IgnoreCase') + if (!$match.Success) { throw 'Unexpected per-user OneDrive uninstall command.' } + $exe = [IO.Path]::GetFullPath($match.Groups[1].Value) + $roots = @((Join-Path $env:LOCALAPPDATA 'Microsoft\OneDrive'), (Join-Path $env:WINDIR 'System32'), (Join-Path $env:WINDIR 'SysWOW64')) + $allowed = @($roots | Where-Object { $exe.StartsWith([IO.Path]::GetFullPath($_).TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase) }).Count -gt 0 + if (!$allowed) { throw 'Per-user OneDrive uninstaller is outside supported locations.' } + Get-Process -Name OneDrive -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq [Diagnostics.Process]::GetCurrentProcess().SessionId } | Stop-Process -Force -ErrorAction Stop + Invoke-OfficeUserUninstaller $exe '/uninstall' + if (Test-Path -LiteralPath $oneDriveKey) { throw 'OneDrive remains registered for this user.' } + } + if (Test-Path -LiteralPath (Join-Path $env:LOCALAPPDATA 'Microsoft\OneDrive\OneDrive.exe')) { throw 'A per-user OneDrive binary remains. Repair/uninstall that installation, then retry user cleanup.' } +} + +function Invoke-OfficeUserCleanup { + param([string]$Workspace) + if (!(Test-Path -LiteralPath (Join-Path $Workspace 'user-cleanup.lock') -PathType Leaf)) { throw 'User cleanup lock file is missing.' } + $deadline = [DateTime]::UtcNow.AddMinutes(5); $lock = $null + do { + try { $lock = [IO.File]::Open((Join-Path $Workspace 'user-cleanup.lock'), [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None) } + catch [IO.IOException] { if ([DateTime]::UtcNow -ge $deadline) { throw 'Another user cleanup is still active; retry at the next sign-in.' }; Start-Sleep -Seconds 2 } + } while ($null -eq $lock) + try { + Clear-OfficeUserCredentials + $preserve = Test-Path -LiteralPath (Join-Path $Workspace 'reinstall-started') + Remove-OfficeUserCompanions -PreserveReinstalledApps:$preserve + } finally { $lock.Dispose() } +} + +$ErrorActionPreference = 'Stop' +$identity = [Security.Principal.WindowsIdentity]::GetCurrent() +$principal = New-Object Security.Principal.WindowsPrincipal($identity) +if ($identity.IsSystem -or $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'User cleanup requires a limited user token, not SYSTEM or an elevated administrator.' } +$marker = "HKCU:\Software\Emberkom\OfficeDeployment\$DeploymentId" +if ((Get-ItemPropertyValue -LiteralPath $marker -Name Status -ErrorAction SilentlyContinue) -eq 'Complete') { exit 0 } +$logFolder = Join-Path $env:LOCALAPPDATA 'Emberkom\OfficeDeployment' +$null = New-Item -ItemType Directory -Path $logFolder -Force +$null = Start-Transcript -Path (Join-Path $logFolder "$DeploymentId.log") -Append +try { + $null = New-Item -Path $marker -Force + Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Running' + Invoke-OfficeUserCleanup -Workspace $PSScriptRoot + Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Complete' +} catch { + Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Failed' + Write-Error $_ -ErrorAction Continue + exit 1 +} finally { $null = Stop-Transcript } diff --git a/rmm/Install-MicrosoftOffice365.ps1 b/rmm/Install-MicrosoftOffice365.ps1 index 528acf0..fa1e143 100644 --- a/rmm/Install-MicrosoftOffice365.ps1 +++ b/rmm/Install-MicrosoftOffice365.ps1 @@ -1,5 +1,19 @@ -. $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1'))) +#Requires -Version 5.1 +# Upload this shim to Syncro. Windows PowerShell 5.1; Run As: System. +# Installs Office, new Outlook, OneDrive, and Teams when included in the subscription. +# See docs/Office365-Deployment.md. +# Configure these [string] Dropdown variables in Syncro: +# [string]$ValidateBeforeChanges - true (default: validate only), false (remove/reinstall) +# [string]$OfficeSubscription - Required; use the exact subscription names in the guide. +# [string]$OfficeArchitecture - Auto (default), 64, 32 +# [string]$UpdateChannel - Current (default), MonthlyEnterprise, SemiAnnual +# [string]$OfficeActivation - User (default), SharedComputer +# [string]$OfficeAppShutdown - Abort (default), Force (unsaved work can be lost) +# Every variable configured in Syncro needs a nonempty value. Do not overwrite injected values. +# Syncro also supplies [string]$COMPANY with the endpoint's company name. +# It is passed through to Office setup; no company dropdown is needed. -# RMM provider must supply the value for $COMPANY variable - -Run-Script -LivePSScript Install-MicrosoftOffice365 \ No newline at end of file +$ErrorActionPreference = 'Stop' +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +. $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1'))) +Run-Script -LivePSScript Install-MicrosoftOffice365 diff --git a/tests/Install-MicrosoftOffice365.Tests.ps1 b/tests/Install-MicrosoftOffice365.Tests.ps1 new file mode 100644 index 0000000..32cbb13 --- /dev/null +++ b/tests/Install-MicrosoftOffice365.Tests.ps1 @@ -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', '')) { + 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 "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 "Download $url") -eq $url) 'Repeated valid link should resolve.' + Assert-OfficeTest ((Get-OfficeOdtDownloadUrl $url.Replace('/', '\/')) -eq $url) 'JSON escaped download link should resolve.' + Assert-OfficeThrows { Get-OfficeOdtDownloadUrl 'blocked' } 'unique current ODT' + Assert-OfficeThrows { Get-OfficeOdtDownloadUrl ($url + ' ' + $url.Replace('20326','20327')) } 'unique current ODT' + Assert-OfficeThrows { Get-OfficeOdtDownloadUrl 'https://download.microsoft.com.evil.test/officedeploymenttool_1.exe' } 'unique current ODT' + 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 +}