Files
management-scripts/Install-MicrosoftOffice365.ps1
T

1441 lines
97 KiB
PowerShell

#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'
ManualScrubUrl = 'https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall'
GetHelpUrl = 'https://aka.ms/SaRA_EnterpriseVersionFiles'
GetHelpExecutable = 'GetHelpCmd.exe'
ScrubArguments = '-S OfficeScrubScenario -AcceptEula -OfficeVersion All'
ScrubRecoveryExitCodes = @(17002, 17004)
HelperVersion = 'EmberkomOfficeUserCleanup-v5'
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
# Windows 10 stays on this feature release; resolve its latest published build
# per channel at run time rather than maintaining a fixed patch/build number.
Windows10OfficeRelease = '2608'
OfficeReleaseHistory = 'https://learn.microsoft.com/en-us/officeupdates/update-history-microsoft365-apps-by-date'
OfficeReleaseHistoryChannels = @{
Current = 'current-channel'
MonthlyEnterprise = 'monthly-enterprise-channel'
SemiAnnual = 'semi-annual-enterprise-channel'
}
OfficeCdnChannels = @{
Current = '492350f6-3a01-4f97-b9c0-c7c6ddf67d60'
MonthlyEnterprise = '55336b82-a18d-4dd6-b5f6-9e5095c314a6'
SemiAnnual = '7ffbc6bf-bc32-4f92-8982-f9dd17fd3114'
}
TeamsUnsupportedWindows10Editions = @('EnterpriseS', 'EnterpriseSN', 'IoTEnterpriseS')
# Teams.exe is classic, msteams.exe is the older personal/Windows Chat client,
# and ms-teams.exe is the current client. Check all three before removal.
RunningAppNames = @('lync', 'winword', 'excel', 'msaccess', 'mstore', 'infopath', 'setlang', 'msouc', 'ois', 'onenote', 'outlook', 'powerpnt', 'mspub', 'groove', 'visio', 'winproj', 'graph', 'teams', 'msteams', '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
MsiBusyAttempts = 5
MsiBusyRetrySeconds = 15
# Installer processes have no separate elapsed-time cutoff; Syncro owns the
# overall run limit (configure 120 minutes). These are post-process checks.
RegistrationCheckAttempts = 61
RegistrationCheckSeconds = 5
AppxRemovalAttempts = 3
UserCleanupWaitMinutes = 20
UserCleanupTaskMinutes = 30
# Deployment headroom, not Microsoft's published minimum system requirements.
# Reserve installation/companion space in addition to a fresh media download.
MinimumInstallFreeSpaceGB = 10
MediaDownloadReserveGB = 6
SetupDiagnosticFileLimit = 8
SetupDiagnosticTailLines = 2000
SetupDiagnosticErrorLines = 12
}
}
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]$defer = $InputValues.DeferReboot
if ([string]::IsNullOrWhiteSpace($defer)) { $defer = 'true' }
$deferReboot = ConvertTo-RmmBoolean -Value $defer -VariableName 'DeferReboot'
[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; DeferReboot = $deferReboot }
# Internal values, populated from the host and Microsoft's release history, not RMM input.
$options.OfficeFeatureRelease = ''; $options.TargetOfficeVersion = ''
# 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
$Options.OfficeFeatureRelease = Get-OfficeFeatureRelease -Build ([int]$os.BuildNumber) -ProductType ([int]$os.ProductType)
$null = Write-Output "Deployment host: $($os.Caption), build $($os.BuildNumber).$($windows.UBR)."
}
function Get-OfficeFeatureRelease {
param([int]$Build, [int]$ProductType)
$definitions = Get-OfficeDeploymentDefinitions
if ($ProductType -eq 1 -and $Build -ge $definitions.MinimumWindowsBuild -and $Build -lt $definitions.Windows11Build) { return $definitions.Windows10OfficeRelease }
return ''
}
function Get-OfficeBuildFromHistory {
param([string]$PageContent, [string]$UpdateChannel, [string]$FeatureRelease)
$definitions = Get-OfficeDeploymentDefinitions
$article = $definitions.OfficeReleaseHistoryChannels[$UpdateChannel]
if (!$article -or $FeatureRelease -notmatch '^\d{4}$') { throw 'Invalid Office release-history selection.' }
$linkPattern = '(^|/)' + [regex]::Escape($article) + '#version-' + $FeatureRelease + '(?:-|$)'
$labelPattern = '^\s*Version\s+' + $FeatureRelease + '\s+\(Build\s+(?<build>\d+\.\d+)\)\s*$'
$content = [Net.WebUtility]::HtmlDecode($PageContent)
$builds = @(foreach ($link in [regex]::Matches($content, '<a\b[^>]*\bhref\s*=\s*["''](?<href>[^"'']+)["''][^>]*>(?<label>.*?)</a>', 'IgnoreCase,Singleline')) {
if ($link.Groups['href'].Value -notmatch $linkPattern) { continue }
$label = $link.Groups['label'].Value -replace '<[^>]+>', ''
if ($label -match $labelPattern) { [version]('16.0.' + $Matches['build']) }
})
$latest = $builds | Sort-Object -Descending -Unique | Select-Object -First 1
if (!$latest) { throw "Microsoft's release history did not identify an Office $FeatureRelease build for $UpdateChannel. Existing Office has not been removed." }
$latest.ToString()
}
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 {
param(
[string]$Root = (Join-Path ([IO.Path]::GetTempPath()) 'EmberkomOfficeDeployment'),
[ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId = ([guid]::NewGuid().ToString('N'))
)
# Executable content must never be writable by a standard user.
# Default to the execution account's temp location (SYSTEM under Syncro).
Assert-OfficeManagedPath $root (Join-Path $root $DeploymentId)
$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 $DeploymentId
$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 New-OfficeUserWorkspace {
param($Media, [string]$Workspace)
# Persist only synchronization state for deferred tasks. They fetch code live;
# no downloaded helper or installation payload survives in ProgramData.
$path = New-OfficeWorkspace -Root (Join-Path $env:ProgramData 'EmberkomOfficeDeployment') -DeploymentId (Split-Path -Leaf $Workspace)
$path
}
function Assert-OfficeWritablePath {
param([string]$Path)
$target = [IO.Path]::GetFullPath($Path)
# Probe the closest existing parent without creating the intended directory.
$parent = $target
while (!(Test-Path -LiteralPath $parent)) {
$parent = Split-Path -Parent $parent
if (!$parent) { throw "No existing parent for deployment path: $target" }
}
Assert-OfficeManagedPath $parent (Join-Path $parent 'office-write-probe')
if (!(Test-Path -LiteralPath $parent -PathType Container)) { throw "Deployment parent is not a directory: $parent" }
$probePath = Join-Path $parent ('OfficeWriteProbe-' + [guid]::NewGuid().ToString('N') + '.tmp')
$probe = $null
try {
$probe = [IO.FileStream]::new($probePath, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None, 1, [IO.FileOptions]::DeleteOnClose)
} catch { throw "Deployment path is not writable: $target (tested $parent). $($_.Exception.Message)" }
finally { if ($probe) { $probe.Dispose() } }
$null = Write-Output "Writable path verified: $target (tested existing directory $parent)."
[pscustomobject]@{ Path=$target; TestedDirectory=$parent }
}
function Test-OfficeDownloadLinks {
param($Options)
$definitions = Get-OfficeDeploymentDefinitions
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$links = @($definitions.OdtPage, "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1", $definitions.GetHelpUrl)
if ($Options.OfficeFeatureRelease) { $links += $definitions.OfficeReleaseHistory }
$channel = $definitions.OfficeCdnChannels[$Options.UpdateChannel]
$links += "https://officecdn.microsoft.com/pr/$channel/Office/Data/v$($Options.OfficeArchitecture).cab"
foreach ($name in @('WebView2', 'NewOutlook', 'OneDrive', 'Teams')) {
if ($name -eq 'Teams' -and !$Options.InstallTeams) { continue }
$installer = $definitions.CompanionInstallers[$name]
if ($name -eq 'OneDrive') {
$arch = if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64' -or $env:PROCESSOR_ARCHITEW6432 -eq 'ARM64') { 'ARM64' } elseif ([Environment]::Is64BitOperatingSystem) { 'x64' } else { 'x86' }
$links += $installer.Uris[$arch]
} else { $links += $installer.Uri }
}
foreach ($uri in $links) {
# HEAD follows redirects but never requests a body or writes a download.
# A server that refuses HEAD fails assessment; do not fall back to GET.
try { $response = Invoke-WebRequest -UseBasicParsing -Method Head -Uri $uri -MaximumRedirection 10 -TimeoutSec $definitions.OdtPageTimeoutSeconds -ErrorAction Stop }
catch { throw "HTTP HEAD check failed for $uri. $($_.Exception.Message)" }
if ([int]$response.StatusCode -ne 200) { throw "HTTP HEAD check for $uri returned $($response.StatusCode); expected 200." }
$null = Write-Output "HTTP HEAD 200: $uri"
[pscustomobject]@{ Uri=$uri; StatusCode=200; Method='HEAD' }
}
}
function Assert-OfficeManagedPath {
param([string]$Root, [string]$Path)
$base = [IO.Path]::GetFullPath($Root).TrimEnd('\')
$target = [IO.Path]::GetFullPath($Path)
if (!$target.StartsWith($base + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "Path is outside the Office deployment root: $target" }
# Check ancestors before enumeration; never follow a junction during deletion or reuse.
for ($cursor = $target; $cursor; $cursor = Split-Path -Parent $cursor) {
if (Test-Path -LiteralPath $cursor) {
if ((Get-Item -LiteralPath $cursor -Force -ErrorAction Stop).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Deployment path traverses a reparse point: $cursor" }
}
}
}
function Get-OfficeManagedFiles {
param([string]$Root, [string]$Path)
Assert-OfficeManagedPath $Root $Path
if (!(Test-Path -LiteralPath $Path)) { return }
$item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
if (!$item.PSIsContainer) { return $item }
foreach ($child in @(Get-ChildItem -LiteralPath $Path -Force -ErrorAction Stop)) {
# Recurse ourselves so a nested junction is rejected BEFORE visiting its target.
Get-OfficeManagedFiles $Root $child.FullName
}
}
function Remove-OfficeManagedItem {
param([string]$Root, [string]$Path)
Assert-OfficeManagedPath $Root $Path
if (!(Test-Path -LiteralPath $Path)) { return }
$null = @(Get-OfficeManagedFiles $Root $Path)
$null = Write-Output "Removing deployment artifact: $Path"
Remove-Item -LiteralPath ([IO.Path]::GetFullPath($Path)) -Recurse -Force -ErrorAction Stop
}
function Assert-OfficeDiskSpace {
param(
[string]$Workspace,
[switch]$DownloadingMedia,
[string[]]$InstallPaths = @($env:WINDIR, $env:ProgramFiles, ${env:ProgramFiles(x86)})
)
$definitions = Get-OfficeDeploymentDefinitions
$required = @{}
foreach ($path in @($InstallPaths | Where-Object { $_ })) {
$drive = [IO.Path]::GetPathRoot([IO.Path]::GetFullPath($path)).TrimEnd('\')
$required[$drive] = [long]($definitions.MinimumInstallFreeSpaceGB * 1GB)
}
if ($DownloadingMedia) {
$stageDrive = [IO.Path]::GetPathRoot([IO.Path]::GetFullPath($Workspace)).TrimEnd('\')
$required[$stageDrive] = [long]$required[$stageDrive] + [long]($definitions.MediaDownloadReserveGB * 1GB)
}
foreach ($drive in ($required.Keys | Sort-Object)) {
if ($drive -notmatch '^[A-Za-z]:$') { throw "Office deployment requires a local drive for disk-space checks: $drive" }
$disk = Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='$drive'" -ErrorAction Stop
if ($null -eq $disk -or $null -eq $disk.FreeSpace) { throw "Could not determine free space on $drive. Existing apps have not been removed." }
$availableGB = [Math]::Round(([long]$disk.FreeSpace / 1GB), 2)
$requiredGB = [Math]::Round(($required[$drive] / 1GB), 2)
$stage = if ($DownloadingMedia) { 'before downloading media' } else { 'after staging, before removal' }
$null = Write-Output "Office disk-space check ${stage}: $drive has $availableGB GB free; deployment requires $requiredGB GB."
if ([long]$disk.FreeSpace -lt $required[$drive]) {
throw "Insufficient disk space on $drive ${stage}: $availableGB GB free; at least $requiredGB GB required. Free space and rerun. Existing apps have not been removed. Deployment media will be cleaned up when installer processes have released it."
}
}
}
function Remove-OfficeStagingFiles {
param([string]$Root, [string]$Workspace)
Assert-OfficeManagedPath $Root $Workspace
$processes = @(Get-CimInstance Win32_Process -ErrorAction Stop)
if (Test-OfficeStagingInUse $Workspace $processes) { throw 'An installer or a process referencing this workspace is still running.' }
# Check every artifact before deleting any part of the payload. The caller holds
# the deployment mutex; these probes also protect against surviving child processes.
$files = @(Get-OfficeManagedFiles $Root $Workspace | Where-Object { $_.Extension -notin @('.log', '.etl') })
foreach ($file in $files) {
$probe = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
$probe.Dispose()
}
foreach ($file in $files) { Remove-OfficeManagedItem $Root $file.FullName }
# Preserve nested logs and their parents, but discard empty payload folders.
foreach ($folder in @(Get-ChildItem -LiteralPath $Workspace -Directory -Recurse -Force -ErrorAction Stop | Sort-Object { $_.FullName.Length } -Descending)) {
Assert-OfficeManagedPath $Root $folder.FullName
if (!@(Get-ChildItem -LiteralPath $folder.FullName -Force -ErrorAction Stop).Count) { Remove-Item -LiteralPath $folder.FullName -Force -ErrorAction Stop }
}
}
function Get-OfficeDeploymentRoots {
$parents = @([IO.Path]::GetTempPath(), (Join-Path $env:WINDIR 'Temp'), (Join-Path $env:WINDIR 'SystemTemp'), $env:ProgramData)
foreach ($profile in @(Get-CimInstance Win32_UserProfile -ErrorAction Stop)) {
if ($profile.LocalPath) { $parents += Join-Path $profile.LocalPath 'AppData\Local\Temp' }
}
@($parents | Where-Object { $_ } | ForEach-Object { [IO.Path]::GetFullPath((Join-Path $_ 'EmberkomOfficeDeployment')).TrimEnd('\') } | Sort-Object -Unique)
}
function Clear-OfficePreviousDeploymentFiles {
# The deployment mutex is held by the caller. Never import options, XML or media
# from these folders; the reserved root and GUID identify our prior workspaces.
$roots = @(Get-OfficeDeploymentRoots)
$processes = @(Get-CimInstance Win32_Process -ErrorAction Stop)
foreach ($root in $roots) {
if (Test-OfficeStagingInUse $root $processes) { throw "A surviving installer is running. Stop the previous deployment before removing old artifacts in $root." }
Assert-OfficeManagedPath $root (Join-Path $root 'path-check')
}
$tasks = @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -match '^Emberkom-OfficeCleanup-[a-f0-9]{32}-S-1-[\d-]+$' })
if (@($tasks | Where-Object { $_.State -in @('Running', 'Queued') }).Count) { throw 'Previous Office user cleanup is still running. Wait for it to finish before redeploying.' }
foreach ($task in $tasks) {
$null = Disable-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -ErrorAction Stop
if ((Get-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -ErrorAction Stop).State -in @('Running', 'Queued')) { throw "Previous user cleanup started during preparation: $($task.TaskName)." }
Unregister-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -Confirm:$false -ErrorAction Stop
$null = Write-Output "Retired previous user cleanup task; this deployment will schedule fresh cleanup: $($task.TaskName)"
}
foreach ($root in $roots) {
# Older validation runs wrote release metadata beside the staging root.
# New runs keep it inside their GUID workspace, including partial downloads.
$parent = Split-Path -Parent $root
if (Test-Path -LiteralPath $parent -PathType Container) {
foreach ($file in @(Get-ChildItem -LiteralPath $parent -File -Filter 'OfficeReleaseHistory-*.html' -ErrorAction Stop | Where-Object { $_.Name -match '^OfficeReleaseHistory-[a-f0-9]{32}\.html$' })) {
Assert-OfficeManagedPath $parent $file.FullName
$probe = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
$probe.Dispose()
Remove-OfficeManagedItem $parent $file.FullName
}
}
if (!(Test-Path -LiteralPath $root)) { continue }
foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -Force -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' })) {
Remove-OfficeStagingFiles $root $folder.FullName
if (!@(Get-ChildItem -LiteralPath $folder.FullName -Force -ErrorAction Stop).Count) { Remove-OfficeManagedItem $root $folder.FullName }
}
}
}
function Test-OfficeStagingInUse {
param([string]$Workspace, [object[]]$Processes)
# Be conservative even when a child installer no longer names its source folder.
foreach ($process in $Processes) {
if ($process.Name -in @('setup.exe', 'odt.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'GetHelpCmd.exe', 'SaRAcmd.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe')) { return $true }
if ($process.Name -eq 'OfficeClickToRun.exe' -and $process.CommandLine -notmatch '(?i)\s/(service|user)\s*$') { return $true }
if ($process.CommandLine -match '(?i)\b(OffScrub[^\s"\\/]*\.(vbs|ps1)|OfficeScrubScenario)\b') { return $true }
foreach ($value in @($process.CommandLine, $process.ExecutablePath)) {
if ($value -and $value.IndexOf($Workspace, [StringComparison]::OrdinalIgnoreCase) -ge 0) { return $true }
}
}
return $false
}
function Complete-OfficeDeploymentFiles {
param([string]$Workspace, [string]$UserWorkspace)
$warnings = @()
# Called from finally on success, failure and restart exits. Only logs remain
# in the download workspace after native processes release it.
try {
$root = Split-Path -Parent $Workspace
Remove-OfficeStagingFiles $root $Workspace
} catch {
$warnings += "$Workspace : $($_.Exception.Message)"
Write-Error "Deployment media cleanup deferred: $($warnings[-1])" -ErrorAction Continue
}
# Pending tasks need only their lock and phase marker, not downloaded code.
if ($UserWorkspace -and $UserWorkspace -ne $Workspace) {
try {
$id = Split-Path -Leaf $UserWorkspace
$tasks = @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -like "Emberkom-OfficeCleanup-$id-*" })
$processes = @(Get-CimInstance Win32_Process -ErrorAction Stop)
if (!$tasks.Count -and !(Test-OfficeStagingInUse $UserWorkspace $processes)) {
Remove-OfficeManagedItem (Split-Path -Parent $UserWorkspace) $UserWorkspace
}
} catch {
$warnings += "$UserWorkspace : $($_.Exception.Message)"
Write-Error "Could not remove completed user cleanup files: $($warnings[-1])" -ErrorAction Continue
}
}
return ,$warnings
}
function Resolve-OfficeTargetVersion {
param($Options, [Parameter(Mandatory=$true)][string]$Workspace)
$Options.TargetOfficeVersion = ''
if (!$Options.OfficeFeatureRelease) { return }
$definitions = Get-OfficeDeploymentDefinitions
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Deployment only. Assessment checks HEAD without resolving/downloading metadata.
$historyPath = Join-Path $Workspace 'office-release-history.html'
try {
Save-OfficeDownload $definitions.OfficeReleaseHistory $historyPath
$Options.TargetOfficeVersion = Get-OfficeBuildFromHistory (Get-Content -LiteralPath $historyPath -Raw -ErrorAction Stop) $Options.UpdateChannel $Options.OfficeFeatureRelease
$null = Write-Output "Windows 10: selected Office $($Options.OfficeFeatureRelease), build $($Options.TargetOfficeVersion), from Microsoft's $($Options.UpdateChannel) release history."
} finally {
if (Test-Path -LiteralPath $historyPath) { Remove-Item -LiteralPath $historyPath -Force -ErrorAction Stop }
}
}
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, [int]$TimeoutSeconds = 0)
$definitions = Get-OfficeDeploymentDefinitions
if (!$TimeoutSeconds) { $TimeoutSeconds = $definitions.DownloadTimeoutSeconds }
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 $TimeoutSeconds -ErrorAction Stop
if ((Get-Item -LiteralPath $Path -ErrorAction Stop).Length -eq 0) { throw 'Download was empty.' }
if ($attempt -gt 1) { $null = Write-Output "Download recovered on attempt ${attempt}: $Uri -> $Path" }
return
} catch {
$reason = $_.Exception.Message
if ($attempt -eq $definitions.DownloadAttempts) {
# The entry point logs and reports the terminal error once to Syncro.
throw "Download failed after $attempt attempts: $Uri -> $Path. $reason"
}
$delay = $definitions.DownloadRetrySeconds * $attempt
# Tools.ps1 logs Write-Output; suppress its echo so a recoverable attempt
# neither pollutes return values nor produces an error in Syncro.
$null = Write-Output "Download attempt $attempt of $($definitions.DownloadAttempts) failed for $Uri -> $Path. $reason Retrying in $delay seconds."
Start-Sleep -Seconds $delay
}
}
}
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)
$definitions = Get-OfficeDeploymentDefinitions
$isMsi = [IO.Path]::GetFileName($FilePath) -ieq 'msiexec.exe'
for ($attempt = 1; ; $attempt++) {
$prefix = if ($attempt -eq 1) { $LogPrefix } else { "$LogPrefix.retry-$attempt" }
$null = Write-Output "Running: $FilePath $Arguments. Process logs: $prefix"
$startedUtc = [DateTime]::UtcNow
$process = Start-Process -FilePath $FilePath -ArgumentList $Arguments -WorkingDirectory (Split-Path -Parent $FilePath) -Wait -PassThru -WindowStyle Hidden -RedirectStandardOutput "$prefix.stdout.log" -RedirectStandardError "$prefix.stderr.log" -ErrorAction Stop
if ($null -eq $process.ExitCode) { throw "No exit code returned from $FilePath." }
$null = Write-Output "Process exited $($process.ExitCode): $FilePath"
if ([IO.Path]::GetFileName($FilePath) -ieq 'setup.exe' -and $process.ExitCode -notin @(0, 3010)) {
# ODT normally writes details to native temp logs, not stdout/stderr.
# Diagnostic collection must never replace the installer's original result.
try { Write-OfficeSetupDiagnostics -SinceUtc $startedUtc }
catch { $null = Write-Output "Could not collect native Office diagnostics: $($_.Exception.Message)" }
}
# Retry only MSI's documented busy result, not arbitrary installer failures.
if (!$isMsi -or $process.ExitCode -ne 1618 -or $attempt -ge $definitions.MsiBusyAttempts) { return [int]$process.ExitCode }
$null = Write-Output "Windows Installer is busy; retrying in $($definitions.MsiBusyRetrySeconds) seconds (attempt $attempt of $($definitions.MsiBusyAttempts))."
Start-Sleep -Seconds $definitions.MsiBusyRetrySeconds
}
}
function Get-OfficeSetupLogFiles {
param(
[DateTime]$SinceUtc,
[string[]]$SearchRoots = @([IO.Path]::GetTempPath(), "$env:WINDIR\Temp", "$env:WINDIR\SystemTemp")
)
$definitions = Get-OfficeDeploymentDefinitions
$finishedUtc = [DateTime]::UtcNow
$files = @(foreach ($root in ($SearchRoots | Select-Object -Unique)) {
try {
if (!(Test-Path -LiteralPath $root -PathType Container)) { continue }
Get-ChildItem -LiteralPath $root -Filter '*.log' -File -ErrorAction Stop | Where-Object {
$_.Length -gt 0 -and $_.LastWriteTimeUtc -ge $SinceUtc.AddSeconds(-5) -and $_.LastWriteTimeUtc -le $finishedUtc -and
!($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -and
($_.Name -like "$env:COMPUTERNAME-*.log" -or $_.Name -match '^(Office|Microsoft[ _-]*Office|ClickToRun|Setup)')
}
} catch { $null = Write-Output "Could not search native Office logs in ${root}: $($_.Exception.Message)" }
})
$files | Sort-Object FullName -Unique | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First $definitions.SetupDiagnosticFileLimit
}
function Write-OfficeSetupDiagnostics {
param(
[DateTime]$SinceUtc,
[string[]]$SearchRoots = @([IO.Path]::GetTempPath(), "$env:WINDIR\Temp", "$env:WINDIR\SystemTemp")
)
$definitions = Get-OfficeDeploymentDefinitions
$files = @(Get-OfficeSetupLogFiles -SinceUtc $SinceUtc -SearchRoots $SearchRoots)
if (!$files.Count) {
$null = Write-Output "No recent nonempty native Office logs found in: $($SearchRoots -join '; '). Empty ODT stdout/stderr files do not contain the underlying setup error."
return
}
foreach ($file in $files) {
$null = Write-Output "Native Office log: $($file.FullName) ($($file.Length) bytes). Recent matching lines below are diagnostic clues, not an automatic diagnosis."
try {
$lines = @(Get-Content -LiteralPath $file.FullName -Tail $definitions.SetupDiagnosticTailLines -ErrorAction Stop |
Where-Object { $_ -match '(?i)\b(error|failed|failure|exception|unexpected)\b|"Error(Code|Type|Message|Details)"' } |
Select-Object -Last $definitions.SetupDiagnosticErrorLines)
if (!$lines.Count) { $null = Write-Output 'No error-like lines found in the inspected tail; retain the full native log for diagnosis.' }
foreach ($line in $lines) { $null = Write-Output "Native Office detail: $line" }
} catch { $null = Write-Output "Could not read native Office log $($file.FullName): $($_.Exception.Message)" }
}
}
function Wait-OfficeResult {
param([scriptblock]$Probe, [string]$Description)
# A probe returns a verified value/true, or nothing/false while registration catches up.
# Read errors still propagate; an inaccessible registry is not proof of removal.
$definitions = Get-OfficeDeploymentDefinitions
for ($attempt = 1; $attempt -le $definitions.RegistrationCheckAttempts; $attempt++) {
$value = & $Probe
if ($value) { return $value }
if ($attempt -eq $definitions.RegistrationCheckAttempts) { return }
if ($attempt -eq 1) { $null = Write-Output "Waiting for $Description (up to $(($definitions.RegistrationCheckAttempts - 1) * $definitions.RegistrationCheckSeconds) seconds)." }
Start-Sleep -Seconds $definitions.RegistrationCheckSeconds
}
}
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 New-OfficeRemovalConfiguration {
param($Options)
$xml = New-Object Xml.XmlDocument
$configuration = $xml.CreateElement('Configuration'); $null = $xml.AppendChild($configuration)
$remove = $xml.CreateElement('Remove'); $remove.SetAttribute('All', 'TRUE'); $null = $configuration.AppendChild($remove)
$display = $xml.CreateElement('Display'); $display.SetAttribute('Level', 'None'); $display.SetAttribute('AcceptEULA', 'TRUE'); $null = $configuration.AppendChild($display)
$property = $xml.CreateElement('Property'); $property.SetAttribute('Name', 'FORCEAPPSHUTDOWN')
$property.SetAttribute('Value', $(if ($Options.OfficeAppShutdown -eq 'Force') { 'TRUE' } else { 'FALSE' })); $null = $configuration.AppendChild($property)
# Remove applies to Click-to-Run. RemoveMSI belongs to the installation configuration:
# ODT removes MSI Office before installing the replacement product in that operation.
return ,$xml
}
function Initialize-OfficeMedia {
param($Options, [string]$Workspace)
$definitions = Get-OfficeDeploymentDefinitions
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
if ($Options.OfficeFeatureRelease -and !$Options.TargetOfficeVersion) { Resolve-OfficeTargetVersion $Options $Workspace }
Assert-OfficeDiskSpace -Workspace $Workspace -DownloadingMedia
# Download only in the install workflow; no persistent cache or cross-run reuse.
$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.' }
$pagePath = Join-Path $Workspace 'odt-download-page.html'
Save-OfficeDownload $definitions.OdtPage $pagePath -TimeoutSeconds $definitions.OdtPageTimeoutSeconds
$url = Get-OfficeOdtDownloadUrl (Get-Content -LiteralPath $pagePath -Raw -ErrorAction Stop)
$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
$removalPath = Join-Path $Workspace 'remove.xml'
$removal = New-OfficeRemovalConfiguration $Options; $removal.Save($removalPath)
$configPath = Join-Path $Workspace 'install.xml'
$config = New-OfficeConfiguration $Options $odtFolder $Options.TargetOfficeVersion; $config.Save($configPath)
$null = Write-Output "Office removal configuration: $($removal.OuterXml)"
$null = Write-Output "Office installation configuration: $($config.OuterXml)"
$null = Write-Output 'Downloading Office installation files before removing installed apps.'
for ($attempt = 1; $attempt -le $definitions.DownloadAttempts; $attempt++) {
$prefix = if ($attempt -eq 1) { 'office-download' } else { "office-download.retry-$attempt" }
$code = Invoke-OfficeProcess $setup "/download `"$configPath`"" (Join-Path $Workspace $prefix)
if ($code -eq 0 -or $attempt -eq $definitions.DownloadAttempts) { break }
$null = Write-Output "Office download failed ($code); retrying download into the same staging folder (attempt $attempt of $($definitions.DownloadAttempts))."
Start-Sleep -Seconds ($definitions.DownloadRetrySeconds * $attempt)
}
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.' }
if ($Options.TargetOfficeVersion -and $versions[0].Name -ne $Options.TargetOfficeVersion) { throw 'Downloaded Office build does not match the Windows 10 target. Existing Office has not been removed.' }
$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" }
}
$companions = Initialize-OfficeCompanionMedia $Workspace -InstallTeams $Options.InstallTeams
$media = [pscustomobject]@{ Setup = $setup; RemovalConfig = $removalPath; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions }
$media
}
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.'
foreach ($process in $running) {
try { Stop-Process -InputObject $process -Force -ErrorAction Stop }
catch {
if (!$process.HasExited) { throw }
$null = Write-Output "Process $($process.Id) exited before it could be stopped; continuing."
}
}
}
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 = Wait-OfficeResult { Get-OfficeMachineWebViewVersion } 'machine WebView2 registration'
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 = @(Wait-OfficeResult { Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.DisplayName -eq $app.Package -and $_.PackageName -like ('*' + $definitions.AppxPublisherSuffix) } } "$($app.Name) provisioning")
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 ', '
$null = Write-Output "Verified $($app.Name) provisioned package: $($packages.PackageName -join ', ')."
} else {
$oneDrive = Wait-OfficeResult { Get-OfficeMachineOneDrive } 'per-machine OneDrive registration'
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)'
}
$key = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration'
if (Test-Path -LiteralPath $key -ErrorAction Stop) {
$c2r = Get-ItemProperty -LiteralPath $key -ErrorAction Stop
if ($c2r.ProductReleaseIds) { [pscustomobject]@{ DisplayName = "Click-to-Run: $($c2r.ProductReleaseIds)" } }
}
}
function Get-OfficeClickToRunState {
# Finished-product inventory misses interrupted installations. Read servicing
# state as evidence only; ODT, not registry deletion, must remove the old setup.
$root = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun'
$present = Test-Path -LiteralPath $root -ErrorAction Stop
$sources = @(); $working = @()
if ($present) {
$keys = @((Get-Item -LiteralPath $root -ErrorAction Stop)) + @(Get-ChildItem -LiteralPath $root -Recurse -ErrorAction Stop)
foreach ($key in $keys) {
$values = Get-ItemProperty -LiteralPath $key.PSPath -ErrorAction Stop
foreach ($property in $values.PSObject.Properties) {
if ($property.Name -like 'PS*') { continue }
foreach ($value in @($property.Value)) {
if ($value -isnot [string] -or !$value.Trim()) { continue }
if ($value -match '(?i)EmberkomOfficeDeployment[\\/]') { $sources += "$($key.Name) : $($property.Name) = $value" }
if ($property.Name -match '^WorkingConfig(uration)?$' -and $value.Trim('{}') -ne '00000000-0000-0000-0000-000000000000') { $working += $value }
}
}
}
}
$service = Get-Service -Name ClickToRunSvc -ErrorAction SilentlyContinue
[pscustomobject]@{ Present=($present -or $null -ne $service); SourceReferences=$sources; WorkingConfiguration=$working }
}
function Test-OfficeFreshInstallState {
[bool](Wait-OfficeResult {
$state = Get-OfficeClickToRunState
!$state.SourceReferences.Count -and !$state.WorkingConfiguration.Count
} 'removal of previous Click-to-Run working configuration and deployment source references')
}
function Assert-OfficeFreshInstallState {
if (!(Test-OfficeFreshInstallState)) {
$state = Get-OfficeClickToRunState
throw "Click-to-Run still retains previous deployment state after ODT removal. Installation stopped to prevent reuse of old content. Working configuration: $($state.WorkingConfiguration -join ', '). Source references: $($state.SourceReferences -join '; '). Arrange an attended Office repair/scrub: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)"
}
}
function Get-OfficeRemovalCorruptionEvidence {
param([DateTime]$SinceUtc)
$finishedUtc = [DateTime]::UtcNow
foreach ($file in @(Get-OfficeSetupLogFiles -SinceUtc $SinceUtc)) {
try {
foreach ($line in @(Get-Content -LiteralPath $file.FullName -Tail (Get-OfficeDeploymentDefinitions).SetupDiagnosticTailLines -ErrorAction Stop)) {
# An exit code alone cannot distinguish corrupt state from network,
# source or policy problems. Require a removal-specific native error
# timestamped during THIS attempt, not an old error in a live log.
if ($line -notmatch '(?i)InvalidDirectory' -or $line -notmatch '(?i)REMOVEINSTALLATION') { continue }
if ($line -notmatch '^\s*(\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2}:\d{2}\.\d{3})\s') { continue }
$stamp = [DateTime]::MinValue
if (![DateTime]::TryParseExact($Matches[1], 'M/d/yyyy H:mm:ss.fff', [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::AssumeLocal, [ref]$stamp)) { continue }
if ($stamp.ToUniversalTime() -lt $SinceUtc.AddSeconds(-1) -or $stamp.ToUniversalTime() -gt $finishedUtc) { continue }
return [pscustomobject]@{ Path=$file.FullName; Detail=$line }
}
} catch { $null = Write-Output "Could not classify Office removal failure from $($file.FullName): $($_.Exception.Message)" }
}
}
function Initialize-OfficeScrubMedia {
param([string]$Workspace)
$definitions = Get-OfficeDeploymentDefinitions
$archivePath = Join-Path $Workspace 'GetHelp.zip'
$folder = Join-Path $Workspace 'GetHelp'
if ((Test-Path -LiteralPath $archivePath) -or (Test-Path -LiteralPath $folder)) { throw 'Scrub media already exists in this run; refusing to reuse it or repeat recovery.' }
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Save-OfficeDownload $definitions.GetHelpUrl $archivePath
# Validate every entry before extraction, including on older PS 5.1 archive modules.
Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem
$archive = [IO.Compression.ZipFile]::OpenRead($archivePath)
try {
foreach ($entry in $archive.Entries) {
if (!$entry.FullName -or $entry.FullName.Contains(':')) { throw 'Unexpected path in Get Help archive.' }
Assert-OfficeManagedPath $folder ([IO.Path]::Combine($folder, $entry.FullName))
}
} finally { $archive.Dispose() }
# Tools.ps1 overrides Expand-Archive with a Path-only wrapper.
Microsoft.PowerShell.Archive\Expand-Archive -LiteralPath $archivePath -DestinationPath $folder -ErrorAction Stop
$files = @(Get-OfficeManagedFiles $Workspace $folder)
$executables = @($files | Where-Object { $_.Name -eq $definitions.GetHelpExecutable })
if ($executables.Count -ne 1) { throw "Microsoft download did not contain exactly one $($definitions.GetHelpExecutable)." }
Assert-OfficeMicrosoftSignature $executables[0].FullName
$executables[0].FullName
}
function Invoke-OfficeScrubRecovery {
param($Media, [string]$Workspace, [string]$Reason)
if ($Media.ScrubAttempted) { throw 'Office scrub recovery was already attempted. Installation stopped; no repeated scrub or install loop will run.' }
$Media | Add-Member -NotePropertyName ScrubAttempted -NotePropertyValue $true -Force
$Media | Add-Member -NotePropertyName ScrubReason -NotePropertyValue $Reason -Force
$null = Write-Output "Office scrub recovery selected: $Reason"
$null = Write-Output 'Running one Microsoft Get Help OfficeScrubScenario attempt. It removes all Office versions, including Visio/Project. Get Help may display a child window despite the hidden launch.'
$scrubber = Initialize-OfficeScrubMedia $Workspace
$prefix = Join-Path $Workspace 'office-scrub'
$code = Invoke-OfficeProcess $scrubber (Get-OfficeDeploymentDefinitions).ScrubArguments $prefix
$output = (Get-Content -LiteralPath "$prefix.stdout.log" -Raw -ErrorAction Stop) + "`n" + (Get-Content -LiteralPath "$prefix.stderr.log" -Raw -ErrorAction Stop)
$results = @([regex]::Matches($output, '(?m)^\s*(\d{2}):') | ForEach-Object { $_.Groups[1].Value })
$null = Write-Output "Get Help scrub result: process $code; scenario results $($results -join ', '). Logs: $prefix"
# 66/68 mean Office was not found, not a verified repair of damaged state.
if ($code -notin @(0, 3010) -or !$results.Count -or @($results | Where-Object { $_ -ne '00' }).Count) { throw "Get Help scrub failed or returned an unverified result (process $code; scenarios $($results -join ', ')). Installation stopped. See $prefix.stdout.log and $prefix.stderr.log." }
$idle = Wait-OfficeResult { !(Test-OfficeStagingInUse $Workspace @(Get-CimInstance Win32_Process -ErrorAction Stop)) } 'Office scrub child processes to finish'
if (!$idle) { throw 'Office scrub processes are still running. Installation stopped to avoid concurrent removal and installation.' }
$removed = Wait-OfficeResult { @(Get-OfficeSuiteInventory).Count -eq 0 } 'all Office registrations to disappear after Get Help scrub'
if (!$removed) { throw "Office remains after Get Help scrub: $((Get-OfficeSuiteInventory).DisplayName -join '; '). Installation stopped." }
Assert-OfficeFreshInstallState
$null = Write-Output 'Office scrub recovery verified. Reporting restart required; DeferReboot controls whether installation can finish before that restart.'
return 3010
}
function Remove-OfficeSuite {
param($Media, [string]$Workspace)
# ODT is the normal path. A single Get Help scrub is reserved for evidence of
# broken removal or residual state, before replacement installation begins.
$existing = @(Get-OfficeSuiteInventory)
$msi = @($existing | Where-Object { $_.WindowsInstaller -eq 1 })
if ($msi.Count) { $null = Write-Output "MSI Office will be removed by ODT RemoveMSI before it installs the replacement suite: $($msi.DisplayName -join '; ')." }
$state = Get-OfficeClickToRunState
if (!@($existing | Where-Object { $_.WindowsInstaller -ne 1 }).Count -and !$state.Present) {
$null = Write-Output 'No Click-to-Run products, service or servicing state detected; skipping the separate ODT removal pass.'
return 0
}
if (!$Media.RemovalConfig -or !(Test-Path -LiteralPath $Media.RemovalConfig -PathType Leaf)) { throw 'The staged silent Office removal configuration is missing.' }
$null = Write-Output 'Silently removing Click-to-Run Office, including incomplete deployments, Visio and Project, with ODT.'
$startedUtc = [DateTime]::UtcNow
$code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.RemovalConfig)`"" (Join-Path $Workspace 'office-remove')
if ($code -notin @(0, 3010)) {
if ($code -in (Get-OfficeDeploymentDefinitions).ScrubRecoveryExitCodes) {
$evidence = Get-OfficeRemovalCorruptionEvidence -SinceUtc $startedUtc
if ($evidence) {
$null = Write-Output "Office scrub trigger evidence: $($evidence.Path) : $($evidence.Detail)"
return Invoke-OfficeScrubRecovery $Media $Workspace "ODT removal exit $code with a current REMOVEINSTALLATION InvalidDirectory error."
}
}
throw "Silent ODT Office removal failed (exit $code). No confirmed removal-corruption evidence was found; automatic scrub was not selected. See logs in $Workspace. Manual troubleshooting: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)"
}
if ($code -eq 3010) { return 3010 }
$removed = Wait-OfficeResult { @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 }).Count -eq 0 } 'Click-to-Run Office removal registration'
if (!$removed) {
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 })
return Invoke-OfficeScrubRecovery $Media $Workspace "Office remains after successful ODT removal: $($remaining.DisplayName -join '; ')."
}
if (!(Test-OfficeFreshInstallState)) { return Invoke-OfficeScrubRecovery $Media $Workspace 'Previous Click-to-Run working configuration or deployment source references remain after successful ODT removal.' }
return 0
}
function Test-OfficeCanDeferRestart {
param($Options, [ValidateSet('Office', 'Companions')][string]$Stage)
if ($Options.DeferReboot -isnot [bool]) { throw 'DeferReboot must be a validated Boolean before deciding whether to continue.' }
if (!$Options.DeferReboot) {
$null = Write-Output "$Stage removal requested a restart. DeferReboot=false; stopping before replacement installation."
return $false
}
# A 3010 result is success with a restart pending, not permission to ignore
# incomplete removal. Verify the old products are gone before deferring it.
$verified = Wait-OfficeResult {
if ($Stage -eq 'Office') { return @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 }).Count -eq 0 }
@(Get-OfficeMachineCompanionEntries).Count -eq 0
} "$Stage removal before deferring its restart"
if ($verified) {
$null = Write-Output "$Stage removal verified. Deferring the requested restart until after deployment; the final result will retain exit code 3010."
return $true
}
$remaining = @(if ($Stage -eq 'Office') { Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 } } else { Get-OfficeMachineCompanionEntries })
$null = Write-Output "Cannot defer the $Stage removal restart: registrations remain for $($remaining.DisplayName -join '; '). Restart and rerun before replacement installation."
return $false
}
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 Test-OfficeMachineMsiProduct {
param([Parameter(Mandatory=$true)][ValidatePattern('^\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\}$')][string]$ProductCode)
if (!('Emberkom.OfficeMachineMsi' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
namespace Emberkom {
public static class OfficeMachineMsi {
[DllImport("msi.dll", CharSet=CharSet.Unicode, ExactSpelling=true)]
private static extern uint MsiEnumProductsExW(string product, string userSid, uint context, uint index, IntPtr code, IntPtr installedContext, IntPtr sid, IntPtr sidLength);
public static uint Find(string product) {
// MSIINSTALLCONTEXT_MACHINE requires a native NULL user SID.
return MsiEnumProductsExW(product, null, 4, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
}
}
}
'@
}
# Read-only MSI enumeration avoids Win32_Product and its repair side effects.
$code = [Emberkom.OfficeMachineMsi]::Find($ProductCode)
if ($code -eq 0) { return $true }
if ($code -in @(259, 1605)) { return $false }
throw "Cannot determine machine MSI registration for $ProductCode (Win32 $code)."
}
function Get-OfficeMachineCompanionEntries {
$definitions = Get-OfficeDeploymentDefinitions
foreach ($entry in @(Get-OfficeUninstallEntries)) {
if ($entry.DisplayName -notin (@('Microsoft OneDrive') + $definitions.TeamsMsiNames)) { continue }
if ($entry.DisplayName -eq 'Microsoft Teams Meeting Add-in for Microsoft Office' -and !(Test-OfficeMachineMsiProduct $entry.PSChildName)) {
# Some per-user add-ins advertise themselves in HKLM. Their registration alone
# does not mean SYSTEM can uninstall them. The user helper checks both hives.
$null = Write-Output "No machine MSI registration for $($entry.DisplayName) $($entry.DisplayVersion), $($entry.PSChildName). Per-user registration will be checked by user cleanup. Registry entry: $($entry.PSPath)"
continue
}
$entry
}
}
function Remove-OfficeAppxEntry {
param([string]$PackageName, [switch]$Provisioned)
$definitions = Get-OfficeDeploymentDefinitions
for ($attempt = 1; $attempt -le $definitions.AppxRemovalAttempts; $attempt++) {
$null = Write-Output "Removing Appx package $PackageName (provisioned=$Provisioned, attempt $attempt)."
try {
if ($Provisioned) { $null = Remove-AppxProvisionedPackage -Online -PackageName $PackageName -AllUsers -ErrorAction Stop }
else { Remove-AppxPackage -Package $PackageName -AllUsers -ErrorAction Stop }
} catch {
# Another removal can already have removed this registration. Verify before failing.
$null = Write-Output "Appx removal reported an error for ${PackageName}: $($_.Exception.Message). Checking state before retrying."
}
$gone = Wait-OfficeResult {
$registered = @(if ($Provisioned) {
Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.PackageName -eq $PackageName }
} else {
Get-AppxPackage -AllUsers -ErrorAction Stop | Where-Object { $_.PackageFullName -eq $PackageName }
})
$registered.Count -eq 0
} "removal of $PackageName"
if ($gone) { return }
}
throw "Appx package remains after $($definitions.AppxRemovalAttempts) removal attempts: $PackageName. Check the diagnostic log."
}
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 })) {
Remove-OfficeAppxEntry $package.PackageName -Provisioned
}
foreach ($package in @(Get-AppxPackage -AllUsers -ErrorAction Stop | Where-Object { $_.Name -in $names })) {
Remove-OfficeAppxEntry $package.PackageFullName
}
$gone = Wait-OfficeResult {
$installed = @(Get-AppxPackage -AllUsers -ErrorAction Stop | Where-Object { $_.Name -in $names })
$provisioned = @(Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.DisplayName -in $names })
($installed.Count + $provisioned.Count) -eq 0
} 'Office/Teams/Outlook Store package removal'
if (!$gone) { throw 'Office/Teams/Outlook Store packages remain after removal.' }
$reboot = $false
foreach ($entry in @(Get-OfficeMachineCompanionEntries)) {
$null = Write-Output "Removing machine companion: $($entry.DisplayName) $($entry.DisplayVersion). Registry entry: $($entry.PSPath)"
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 (!$reboot) { $null = Wait-OfficeResult { @(Get-OfficeMachineCompanionEntries).Count -eq 0 } 'machine companion removal registration' }
$remaining = @(Get-OfficeMachineCompanionEntries)
if ($remaining.Count) {
$details = ($remaining | ForEach-Object { "$($_.DisplayName) $($_.DisplayVersion) [$($_.PSPath)]" }) -join '; '
$null = Write-Output "Machine companion registrations remaining after removal: $details"
if (!$reboot) { throw "Machine companion registrations remain after removal: $details. Check uninstall logs in $Workspace. Office removal/installation has not started." }
}
$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 New-OfficeUserCleanupCommand {
param([ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId)
$definitions = Get-OfficeDeploymentDefinitions
$uri = "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1".Replace("'", "''")
$version = $definitions.HelperVersion.Replace("'", "''")
$command = @'
$ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
try {
$client = New-Object Net.WebClient
try { $source = $client.DownloadString('__URI__') } finally { $client.Dispose() }
if (!$source.Contains('__VERSION__')) { throw 'Office user cleanup helper version does not match its deployment.' }
& ([scriptblock]::Create($source)) -DeploymentId '__ID__'
} catch { Write-Error $_ -ErrorAction Continue; exit 1 }
'@
$command = $command.Replace('__URI__', $uri).Replace('__VERSION__', $version).Replace('__ID__', $DeploymentId)
[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
}
function Start-OfficeUserCleanup {
param([object[]]$Profiles, $Media, [string]$Workspace)
$definitions = Get-OfficeDeploymentDefinitions
$deploymentId = Split-Path -Leaf $Workspace; $tasks = @(); $registrationFailures = @()
foreach ($profile in $Profiles) {
$name = "Emberkom-OfficeCleanup-$deploymentId-$($profile.SID)"
try {
$command = New-OfficeUserCleanupCommand $deploymentId
$action = New-ScheduledTaskAction -Execute "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand $command" -ErrorAction Stop
$principal = New-ScheduledTaskPrincipal -UserId $profile.SID -LogonType Interactive -RunLevel Limited -ErrorAction Stop
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $profile.SID -ErrorAction Stop
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes $definitions.UserCleanupTaskMinutes) -MultipleInstances IgnoreNew -ErrorAction Stop
$null = Write-Output "Registering user cleanup task: $name"
$null = Register-ScheduledTask -TaskName $name -Action $action -Principal $principal -Trigger $trigger -Settings $settings -Force -ErrorAction Stop
} catch {
# A profile can outlive its account, or account lookup can be unavailable.
# Do not leave Office uninstalled because this user's task cannot be created.
# Keep it separate from pending tasks: signing in cannot retry a missing task.
$registrationFailures += [pscustomobject]@{ SID=$profile.SID; ProfilePath=$profile.LocalPath; Error=$_.Exception.Message }
Write-Error "User cleanup task registration failed for $($profile.SID) ($($profile.LocalPath)): $($_.Exception.Message). Continuing Office installation and cleanup scheduling for other users; this user's task needs review." -ErrorAction Continue
continue
}
$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') {
try { Unregister-ScheduledTask -TaskName $task.Name -Confirm:$false -ErrorAction Stop }
catch { $null = Write-Output "Cleanup completed, but its task could not be unregistered: $($task.Name). The Complete marker makes it a no-op. $($_.Exception.Message)" }
}
else { $pending += $task.SID; $null = Write-Output "Cleanup pending for $($task.SID); task $($task.Name) runs at their next sign-in." }
}
[pscustomobject]@{ PendingUserSids=$pending; RegistrationFailures=$registrationFailures }
}
function Install-OfficeMedia {
param($Options, $Media, [string]$Workspace)
$msi = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 })
$code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.Config)`"" (Join-Path $Workspace 'office-install')
if ($code -notin @(0, 3010)) { throw "Office installation failed (exit $code). Diagnostic logs remain in $Workspace; disposable media is cleaned up after installer processes finish. Review the Native Office log/detail entries in the diagnostic log; Click-to-Run writes its underlying errors to the execution account's temp folder or Windows\Temp. The exit code alone does not identify the cause. No automatic scrub is attempted after replacement installation begins." }
$msiRemoved = Wait-OfficeResult { @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 }).Count -eq 0 } 'legacy MSI Office removal by ODT'
if (!$msiRemoved) {
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 })
throw "MSI Office remains after ODT RemoveMSI: $($remaining.DisplayName -join '; '). Deployment is incomplete; the new suite may already be installed. No automatic scrub is attempted after replacement installation begins. Arrange an attended manual scrub if needed: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)"
}
$platform = if ($Options.OfficeArchitecture -eq '64') { 'x64' } else { 'x86' }
$verified = Wait-OfficeResult {
$key = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration'
if (!(Test-Path -LiteralPath $key -ErrorAction Stop)) { return $false }
$installed = Get-ItemProperty -LiteralPath $key -ErrorAction Stop
if ($Options.ProductId -notin ($installed.ProductReleaseIds -split ',') -or $installed.Platform -ne $platform -or $installed.VersionToReport -notmatch (Get-OfficeDeploymentDefinitions).OfficeBuildPattern) { return $false }
# Unpinned ODT can install a newer build than this run's earlier download.
# Windows 10 must still match its explicitly selected compatible build.
if ($Options.TargetOfficeVersion) {
if ($installed.VersionToReport -ne $Options.TargetOfficeVersion) { return $false }
} elseif ([version]$installed.VersionToReport -lt [version]$Media.Version) { return $false }
$installed.VersionToReport
} 'the selected Office product, architecture, and version'
if (!$verified) { throw 'Setup exited successfully but the installed product, architecture, or version did not match.' }
$Media.Version = [string]$verified
$null = Write-Output "Verified installed Office $($Media.Version) ($($Options.ProductId), $platform)."
# Microsoft requires a restart to finish MSI removal even when setup doesn't enforce it.
if ($msi.Count) { $null = Write-Output 'Legacy MSI Office removal was verified. A restart is required to finish removal; no automatic reboot was requested.'; return 3010 }
$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.' }
if ($Options.DeferReboot -isnot [bool]) { throw 'DeferReboot must be a validated Boolean before running the workload.' }
Assert-OfficeDeploymentHost $Options
$mutex = New-Object Threading.Mutex($false, 'Global\EmberkomOfficeDeployment')
$locked = $false
$workspace = $null; $userWorkspace = $null; $receipt = $null; $completed = $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." }
$null = Write-Output "Office request: $($Options.OfficeSubscription) / $($Options.ProductId), $($Options.OfficeArchitecture)-bit, $($Options.UpdateChannel), ValidateBeforeChanges=$($Options.ValidateBeforeChanges), DeferReboot=$($Options.DeferReboot)."
$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." }
}
$stagingRoot = Join-Path ([IO.Path]::GetTempPath()) 'EmberkomOfficeDeployment'
$paths = @($stagingRoot, (Join-Path $env:ProgramData 'EmberkomOfficeDeployment'), $env:ProgramFiles, ${env:ProgramFiles(x86)})
$writablePaths = @($paths | Where-Object { $_ } | Select-Object -Unique | ForEach-Object { Assert-OfficeWritablePath $_ })
if ($Options.ValidateBeforeChanges) {
Assert-OfficeDiskSpace -Workspace $stagingRoot -DownloadingMedia
$downloadChecks = @(Test-OfficeDownloadLinks $Options)
$existingOffice = @(Get-OfficeSuiteInventory | ForEach-Object { $_.DisplayName })
$state = Get-OfficeClickToRunState
$null = Write-Output 'Assessment passed. HTTP HEAD checks returned 200; no response bodies downloaded or deployment directory created. Exact ODT package and Office build resolution/signature verification occur only during deployment.'
return [pscustomobject]@{
OfficeDeploymentStatus='ValidationPassed'; ExitCode=0; ValidateBeforeChanges=$true
ProductId=$Options.ProductId; OfficeVersion=$Options.TargetOfficeVersion; Architecture=$Options.OfficeArchitecture
UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams; OfficeRemovalMethod='SilentODT'; DeferReboot=$Options.DeferReboot
Workspace=$null; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps; MediaDownloaded=$false
WritablePaths=$writablePaths; DownloadChecks=$downloadChecks; ClickToRunState=$state; OfficeFeatureRelease=$Options.OfficeFeatureRelease; MetadataResolved=$false
ScrubRecoveryPolicy='One Get Help scrub for confirmed removal corruption or residual state after successful ODT removal; deployment only.'
NextStep='Set ValidateBeforeChanges=false to download, verify, deploy, and clean up installation media. Prerequisites are checked again.'
}
}
Clear-OfficePreviousDeploymentFiles
Assert-OfficeDiskSpace -Workspace $stagingRoot -DownloadingMedia
$workspace = New-OfficeWorkspace
$null = Write-Output "Temporary deployment workspace: $workspace"
# Keep the request in a diagnostic log; XML and options are never reused.
$Options | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $workspace 'deployment-options.log') -Encoding UTF8
Resolve-OfficeTargetVersion $Options $workspace
$media = Initialize-OfficeMedia $Options $workspace
Assert-OfficeDiskSpace -Workspace $workspace
Stop-OfficeDeploymentApps $Options
$reboot = Remove-OfficeCompanionApps $workspace
if ($reboot -and !(Test-OfficeCanDeferRestart $Options 'Companions')) {
$null = Write-Output 'Companion app removal requires a restart. Restart and rerun; Office installation has not started.'
$receipt = [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'CompanionRemoval'; Workspace = $workspace; PendingUserSids = @(); ArtifactCleanupPending=$false }
return $receipt
}
$removalCode = Remove-OfficeSuite $media $workspace
if ($removalCode -eq 3010 -and !(Test-OfficeCanDeferRestart $Options 'Office')) {
$null = Write-Output 'Office removal requires a restart. Restart and rerun; replacement installation has not started.'
$receipt = [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @(); ArtifactCleanupPending=$false; ScrubRecoveryAttempted=[bool]$media.ScrubAttempted; ScrubRecoveryReason=$media.ScrubReason }
return $receipt
}
Assert-OfficeFreshInstallState
foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile }
$userWorkspace = $workspace
if ($profiles.Count) { $userWorkspace = New-OfficeUserWorkspace $media $workspace }
$userCleanup = Start-OfficeUserCleanup $profiles $media $userWorkspace
$pending = @($userCleanup.PendingUserSids)
$registrationFailures = @($userCleanup.RegistrationFailures)
Set-OfficeReinstallPhase $userWorkspace
$code = Install-OfficeMedia $Options $media $workspace
$companions = Install-OfficeCompanionApps $media.Companions $workspace -InstallTeams $Options.InstallTeams
if ($reboot -or $removalCode -eq 3010 -or $companions.ExitCode -eq 3010) { $code = 3010 }
$status = if ($registrationFailures.Count) { 'InstalledWithUserCleanupIncomplete' } elseif ($pending.Count) { 'InstalledWithUserCleanupPending' } else { 'Installed' }
$null = Write-Output "$status. Office $($media.Version), $($Options.ProductId). 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.'
$completed = $true
$receipt = [pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if (($pending.Count -or $registrationFailures.Count) -and $code -eq 0) { 2 } else { $code }); RestartRequired=($code -eq 3010); DeferReboot=$Options.DeferReboot; ValidateBeforeChanges=$false; Workspace = $workspace; UserCleanupWorkspace=$(if ($profiles.Count) { $userWorkspace } else { $null }); PendingUserSids = $pending; UserCleanupRegistrationFailures = $registrationFailures; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version; MediaDownloaded=$true; ArtifactCleanupPending=$false; ScrubRecoveryAttempted=[bool]$media.ScrubAttempted; ScrubRecoveryReason=$media.ScrubReason }
return $receipt
} finally {
if ($workspace) {
try { $cleanupWarnings = Complete-OfficeDeploymentFiles $workspace $(if ($completed) { $userWorkspace } else { $null }) }
catch { $cleanupWarnings = @($_.Exception.Message); Write-Error "Office media cleanup failed: $($cleanupWarnings[0])" -ErrorAction Continue }
if ($receipt) {
$receipt.ArtifactCleanupPending = $cleanupWarnings.Count -gt 0
if ($cleanupWarnings.Count -and $receipt.ExitCode -eq 0) { $receipt.ExitCode = 2; $receipt.OfficeDeploymentStatus = 'InstalledWithArtifactCleanupPending' }
}
if ($cleanupWarnings.Count) { $null = Write-Output 'Some deployment artifacts could not be removed safely. Stop surviving installers before rerunning; the next deployment must clean prior artifacts before downloading fresh media.' }
}
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, writable paths and HTTP HEAD 200 responses. No metadata or payload downloads, deployment directory, artifact cleanup, app shutdown, or installation will run.'
} else {
Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: clearing prior artifacts, downloading fresh media, then silently removing Office with ODT and installing the selected apps. Download workspaces retain only logs after cleanup.'
}
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*') {
if ($deployment[0].UserCleanupRegistrationFailures.Count) { Microsoft.PowerShell.Utility\Write-Output 'WARNING: Installation succeeded, but some user cleanup tasks could not be registered. Review UserCleanupRegistrationFailures; signing in alone cannot retry a task that was not created.' }
if ($deployment[0].ArtifactCleanupPending) { Microsoft.PowerShell.Utility\Write-Output 'WARNING: Installation succeeded, but some deployment files could not be cleaned up. See the diagnostic log; no background cleanup is scheduled.' }
if ($deployment[0].ExitCode -eq 3010) { Microsoft.PowerShell.Utility\Write-Output 'A restart is required to finish deployment; no automatic reboot was requested.' }
Microsoft.PowerShell.Utility\Write-Output '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', 'DeferReboot', '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
}
}