#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. #> 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 } } 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 } 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 } 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.' } } 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 } 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" } 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 } }