1178 lines
79 KiB
PowerShell
1178 lines
79 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'
|
|
HelperVersion = 'EmberkomOfficeUserCleanup-v4'
|
|
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'
|
|
}
|
|
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).
|
|
$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)
|
|
# Only deferred user cleanup must survive routine temp purges. SYSTEM's temp
|
|
# directory may also be inaccessible to the limited users who run this helper.
|
|
$path = New-OfficeWorkspace -Root (Join-Path $env:ProgramData 'EmberkomOfficeDeployment') -DeploymentId (Split-Path -Leaf $Workspace)
|
|
$helper = Join-Path $path 'Office-UserCleanup.ps1'
|
|
Copy-Item -LiteralPath $Media.Helper -Destination $helper -ErrorAction Stop
|
|
$Media.Helper = $helper
|
|
$path
|
|
}
|
|
|
|
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 Get-OfficeStagingNames {
|
|
# Only our downloaded artifacts; never Office's installed files or servicing caches.
|
|
@('ODT', 'odt.exe', 'odt-download-page.html', 'GetHelp', 'GetHelp.zip', 'media-cache.json')
|
|
foreach ($installer in (Get-OfficeDeploymentDefinitions).CompanionInstallers.Values) { $installer.File }
|
|
}
|
|
|
|
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.
|
|
foreach ($name in (Get-OfficeStagingNames)) {
|
|
foreach ($file in @(Get-OfficeManagedFiles $Root (Join-Path $Workspace $name))) {
|
|
$probe = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
|
|
$probe.Dispose()
|
|
}
|
|
}
|
|
foreach ($name in (Get-OfficeStagingNames)) { Remove-OfficeManagedItem $Root (Join-Path $Workspace $name) }
|
|
}
|
|
|
|
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', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe')) { 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. Keep small logs/XML
|
|
# for diagnosis; remove only our disposable media after native processes release it.
|
|
try {
|
|
$root = Split-Path -Parent $Workspace
|
|
Remove-OfficeStagingFiles $root $Workspace
|
|
Remove-OfficeManagedItem $root (Join-Path $Workspace 'Office-UserCleanup.ps1')
|
|
} catch {
|
|
$warnings += "$Workspace : $($_.Exception.Message)"
|
|
Write-Error "Deployment media cleanup deferred: $($warnings[-1])" -ErrorAction Continue
|
|
}
|
|
# Only pass UserWorkspace after a completed installation. Pending helpers survive.
|
|
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)
|
|
$Options.TargetOfficeVersion = ''
|
|
if (!$Options.OfficeFeatureRelease) { return }
|
|
$definitions = Get-OfficeDeploymentDefinitions
|
|
# Small metadata only, including in validation. No persistent staging directory.
|
|
$historyPath = Join-Path ([IO.Path]::GetTempPath()) ('OfficeReleaseHistory-' + [guid]::NewGuid().ToString('N') + '.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 Write-OfficeSetupDiagnostics {
|
|
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 = @($files | Sort-Object FullName -Unique | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First $definitions.SetupDiagnosticFileLimit)
|
|
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 }
|
|
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 '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 Remove-OfficeSuite {
|
|
param($Media, [string]$Workspace)
|
|
# Get Help can create an interactive elevated child despite a hidden SYSTEM parent.
|
|
# Never fall back to it automatically. ODT owns the supported silent removal path.
|
|
$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 '; ')." }
|
|
if (!@($existing | Where-Object { $_.WindowsInstaller -ne 1 }).Count) {
|
|
$null = Write-Output 'No non-MSI Office products 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 Visio and Project, with ODT.'
|
|
$code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.RemovalConfig)`"" (Join-Path $Workspace 'office-remove')
|
|
$manual = "No interactive scrubber was launched. Arrange an attended manual scrub if needed: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)"
|
|
if ($code -notin @(0, 3010)) { throw "Silent ODT Office removal failed (exit $code). See logs in $Workspace. $manual" }
|
|
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 })
|
|
throw "Office remains after silent ODT removal: $($remaining.DisplayName -join '; '). Installation stopped. $manual"
|
|
}
|
|
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 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 {
|
|
$action = New-ScheduledTaskAction -Execute "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$($Media.Helper)`" -DeploymentId $deploymentId" -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 interactive scrubber was launched." }
|
|
$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 interactive scrubber was launched. 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 the earlier validation 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." }
|
|
}
|
|
Resolve-OfficeTargetVersion $Options
|
|
$stagingRoot = Join-Path ([IO.Path]::GetTempPath()) 'EmberkomOfficeDeployment'
|
|
Assert-OfficeDiskSpace -Workspace $stagingRoot -DownloadingMedia
|
|
if ($Options.ValidateBeforeChanges) {
|
|
$existingOffice = @(Get-OfficeSuiteInventory | ForEach-Object { $_.DisplayName })
|
|
$null = Write-Output 'Validation passed. No installation media downloaded or staging workspace created. Installation will repeat prerequisites and verify downloads before removal.'
|
|
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
|
|
NextStep='Set ValidateBeforeChanges=false to download, verify, deploy, and clean up installation media. Prerequisites are checked again.'
|
|
}
|
|
}
|
|
$workspace = New-OfficeWorkspace
|
|
$null = Write-Output "Temporary deployment workspace: $workspace"
|
|
$Options | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $workspace 'options.json') -Encoding UTF8
|
|
$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 }
|
|
return $receipt
|
|
}
|
|
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 }
|
|
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) { $null = Write-Output 'Some deployment media remains; review the log and use OfficeStaging cleanup after installer processes finish.' }
|
|
}
|
|
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 optional release metadata. No installation media downloads, staging, app shutdown, Office/user cleanup, or installation will run.'
|
|
} else {
|
|
Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: validating and staging media, then silently removing Office with ODT 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*') {
|
|
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
|
|
}
|
|
}
|