2026-10-12 18:31:00 -04:00
# 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'
2026-10-21 09:30:15 -04:00
ManualScrubUrl = 'https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall'
HelperVersion = 'EmberkomOfficeUserCleanup-v4'
2026-10-12 18:31:00 -04:00
Language = 'en-us'
OfficeBuildPattern = '^16\.0\.\d+\.\d+$'
OdtExcludedApps = @ ( 'Groove' , 'OneDrive' , 'Lync' , 'Teams' , 'OutlookForWindows' )
CompanionInstallers = @ {
WebView2 = @ { File = 'MicrosoftEdgeWebview2Setup.exe' ; Uri = 'https://go.microsoft.com/fwlink/p/?LinkId=2124703' ; Arguments = '/silent /install' }
Teams = @ { File = 'teamsbootstrapper.exe' ; Uri = 'https://go.microsoft.com/fwlink/?linkid=2243204&clcid=0x409' ; Arguments = '-p' ; Package = 'MSTeams' }
NewOutlook = @ { File = 'OutlookSetup.exe' ; Uri = 'https://go.microsoft.com/fwlink/?linkid=2207851' ; Arguments = '--provision true --quiet --start-' ; Package = 'Microsoft.OutlookForWindows' }
OneDrive = @ { File = 'OneDriveSetup.exe' ; Arguments = '/allusers /silent' ; Uris = @ {
ARM64 = 'https://go.microsoft.com/fwlink/?linkid=2282608'
x64 = 'https://go.microsoft.com/fwlink/?linkid=844652'
x86 = 'https://go.microsoft.com/fwlink/?linkid=2181213'
} }
}
WebViewClientId = '{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}'
AppxPublisherSuffix = '_8wekyb3d8bbwe'
MinimumWindowsBuild = 19041
MinimumServerBuild = 20348
MinimumServerRevision = 2402
Windows11Build = 22000
TeamsUnsupportedWindows10Editions = @ ( 'EnterpriseS' , 'EnterpriseSN' , 'IoTEnterpriseS' )
2026-10-22 00:16:40 -04:00
# 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' )
2026-10-12 18:31:00 -04:00
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
2026-10-21 09:30:15 -04:00
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
MediaCacheDays = 7
2026-10-12 18:31:00 -04:00
}
}
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'
2026-10-21 09:30:15 -04:00
[ string ] $defer = $InputValues . DeferReboot
if ([ string ]:: IsNullOrWhiteSpace ( $defer )) { $defer = 'true' }
$deferReboot = ConvertTo-RmmBoolean -Value $defer -VariableName 'DeferReboot'
2026-10-12 18:31:00 -04:00
[ 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 = '' }
2026-10-21 09:30:15 -04:00
$options = @ { OfficeSubscription = $subscription ; ProductId = $plans [ $subscription ]; Company = $company ; ValidateBeforeChanges = $validateOnly ; DeferReboot = $deferReboot }
2026-10-12 18:31:00 -04:00
# Derive this from the validated product mapping, including standalone Apps plans and legacy aliases.
$options . InstallTeams = $options . ProductId -in $definitions . TeamsProducts
foreach ( $name in $choices . Keys ) {
[ string ] $value = $InputValues [ $name ]
$value = $value . Trim ()
if (! $value ) { $value = $choices [ $name ][ 0 ] }
if ( $value -notin $choices [ $name ]) { throw "Invalid ${name} : ' $value '. Allowed: $( $choices [ $name ] -join ', ' ) ." }
$options [ $name ] = $value
}
if ( $options . OfficeActivation -eq 'SharedComputer' -and $options . ProductId -like 'O365Business*' -and $subscription -notin $definitions . SharedComputerBusinessPlans ) {
throw 'Shared computer activation requires Business Premium or an eligible enterprise subscription.'
}
if ( $options . OfficeArchitecture -eq 'Auto' ) { $options . OfficeArchitecture = if ([ Environment ]:: Is64BitOperatingSystem ) { '64' } else { '32' } }
if ( $options . OfficeArchitecture -eq '64' -and ![ Environment ]:: Is64BitOperatingSystem ) { throw '64-bit Office requires 64-bit Windows.' }
if ( $options . OfficeArchitecture -eq '32' -and ( $env:PROCESSOR_ARCHITECTURE -eq 'ARM64' -or $env:PROCESSOR_ARCHITEW6432 -eq 'ARM64' )) { throw '32-bit Office is not supported on Windows ARM64.' }
[ pscustomobject ] $options
}
function Assert-OfficeDeploymentHost {
param ( $Options )
$principal = New-Object Security . Principal . WindowsPrincipal ([ Security.Principal.WindowsIdentity ]:: GetCurrent ())
if (! $principal . IsInRole ([ Security.Principal.WindowsBuiltInRole ]:: Administrator )) { throw 'Office deployment requires SYSTEM or an elevated administrator.' }
if ([ Environment ]:: Is64BitOperatingSystem -and ![ Environment ]:: Is64BitProcess ) { throw 'Office deployment must run in native Windows PowerShell; the main script entry point handles relaunch.' }
if ( $PSVersionTable . PSEdition -ne 'Desktop' -or $PSVersionTable . PSVersion . Major -ne 5 -or $PSVersionTable . PSVersion . Minor -ne 1 ) { throw 'Run in Windows PowerShell 5.1 for Appx support.' }
foreach ( $command in @ ( 'Get-AppxPackage' , 'Remove-AppxPackage' , 'Get-AppxProvisionedPackage' , 'Remove-AppxProvisionedPackage' , 'Register-ScheduledTask' )) { $null = Get-Command $command -ErrorAction Stop }
$os = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop
$windows = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction Stop
Assert-OfficeCompanionPlatform -Build ([ int ] $os . BuildNumber ) -ProductType ([ int ] $os . ProductType ) -Revision ([ int ] $windows . UBR ) -EditionId $windows . EditionID -InstallTeams $Options . InstallTeams
}
function Assert-OfficeCompanionPlatform {
param ([ int ] $Build , [ int ] $ProductType , [ int ] $Revision , [ string ] $EditionId , [ bool ] $InstallTeams = $false )
$definitions = Get-OfficeDeploymentDefinitions
if ( $Build -lt $definitions . MinimumWindowsBuild ) { throw "Teams and new Outlook require Windows build $( $definitions . MinimumWindowsBuild ) or newer. No apps have been removed." }
if ( $ProductType -ne 1 -and ( $Build -lt $definitions . MinimumServerBuild -or ( $Build -eq $definitions . MinimumServerBuild -and $Revision -lt $definitions . MinimumServerRevision ))) { throw "New Outlook requires Windows Server 2022 build $( $definitions . MinimumServerBuild ) . $( $definitions . MinimumServerRevision ) or newer. No apps have been removed." }
if ( $InstallTeams -and $ProductType -eq 1 -and $Build -lt $definitions . Windows11Build -and $EditionId -in $definitions . TeamsUnsupportedWindows10Editions ) { throw 'Teams desktop does not support Windows 10 LTSC. No apps have been removed.' }
}
function New-OfficeWorkspace {
2026-10-21 09:30:15 -04:00
param (
[ string ] $Root = ( Join-Path ([ IO.Path ]:: GetTempPath ()) 'EmberkomOfficeDeployment' ),
[ ValidatePattern ( '^[a-f0-9]{32}$' )][ string ] $DeploymentId = ([ guid ]:: NewGuid (). ToString ( 'N' ))
)
2026-10-12 18:31:00 -04:00
# Executable content must never be writable by a standard user.
2026-10-21 09:30:15 -04:00
# Default to the execution account's temp location (SYSTEM under Syncro).
2026-10-12 18:31:00 -04:00
$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
2026-10-21 09:30:15 -04:00
$path = Join-Path $root $DeploymentId
2026-10-12 18:31:00 -04:00
$null = New-Item -ItemType Directory -Path $path -ErrorAction Stop
$null = New-Item -ItemType File -Path ( Join-Path $path 'user-cleanup.lock' ) -ErrorAction Stop
$path
}
2026-10-21 09:30:15 -04:00
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 Remove-OfficeStagingFiles {
param ([ string ] $Root , [ string ] $Workspace )
Assert-OfficeManagedPath $Root $Workspace
foreach ( $name in ( Get-OfficeStagingNames )) { Remove-OfficeManagedItem $Root ( Join-Path $Workspace $name ) }
}
function Complete-OfficeDeploymentFiles {
param ([ string ] $Workspace , [ string ] $UserWorkspace , [ string ] $PreviousRoot )
$warnings = @ ()
# This runs only after installation succeeds. No scheduled housekeeping is created.
# Include older temp attempts, but never files still referenced by another process.
$root = Split-Path -Parent $Workspace
$processes = @ ( Get-CimInstance Win32_Process -ErrorAction Stop )
foreach ( $folder in @ ( Get-ChildItem -LiteralPath $root -Directory -ErrorAction Stop | Where-Object { $_ . Name -match '^[a-f0-9]{32}$' })) {
try {
Assert-OfficeManagedPath $root $folder . FullName
if (!( Test-Path -LiteralPath ( Join-Path $folder . FullName 'options.json' ))) { continue }
if ( @ ( $processes | Where-Object { $_ . CommandLine -and $_ . CommandLine . IndexOf ( $folder . FullName , [ StringComparison ]:: OrdinalIgnoreCase ) -ge 0 }). Count ) {
$warnings += " $( $folder . FullName ) is still in use."
continue
}
Remove-OfficeManagedItem $root $folder . FullName
} catch {
$warnings += " $( $folder . FullName ) : $( $_ . Exception . Message ) "
Write-Error "Could not remove temporary deployment files: $( $warnings [ -1 ]) " -ErrorAction Continue
}
}
# Earlier versions put downloads in ProgramData. Remove only their known staging
# artifacts after success; old user tasks may still need their helper/lock files.
if ( $PreviousRoot -and $PreviousRoot -ne $root -and ( Test-Path -LiteralPath $PreviousRoot )) {
foreach ( $folder in @ ( Get-ChildItem -LiteralPath $PreviousRoot -Directory -ErrorAction Stop | Where-Object { $_ . Name -match '^[a-f0-9]{32}$' })) {
try {
Assert-OfficeManagedPath $PreviousRoot $folder . FullName
if (!( Test-Path -LiteralPath ( Join-Path $folder . FullName 'options.json' ))) { continue }
if ( @ ( $processes | Where-Object { $_ . CommandLine -and $_ . CommandLine . IndexOf ( $folder . FullName , [ StringComparison ]:: OrdinalIgnoreCase ) -ge 0 }). Count ) { continue }
Remove-OfficeStagingFiles $PreviousRoot $folder . FullName
} catch {
$warnings += " $( $folder . FullName ) : $( $_ . Exception . Message ) "
Write-Error "Could not remove older deployment downloads: $( $warnings [ -1 ]) " -ErrorAction Continue
}
}
}
if ( $UserWorkspace -and $UserWorkspace -ne $Workspace ) {
try {
# Start-OfficeUserCleanup already unregisters completed tasks. Preserve the
# helper whenever any task remains, including a failed unregister attempt.
$id = Split-Path -Leaf $UserWorkspace
$tasks = @ ( Get-ScheduledTask -ErrorAction Stop | Where-Object { $_ . TaskName -like "Emberkom-OfficeCleanup- $id -*" })
if (! $tasks . Count ) { 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 Get-OfficeMediaCacheKey {
param ( $Options )
$definitions = Get-OfficeDeploymentDefinitions
# Company, activation, app shutdown, and reboot choices affect XML, not the payload.
$contract = [ ordered ] @ {
Schema = 1 ; Product = $Options . ProductId ; Architecture = $Options . OfficeArchitecture
Channel = $Options . UpdateChannel ; Language = $definitions . Language
OdtPage = $definitions . OdtPage ; ExcludedApps = $definitions . OdtExcludedApps
Downloads = @ ( Get-OfficeCompanionDownloads -InstallTeams $Options . InstallTeams | ForEach-Object { " $( $_ . Name ) | $( $_ . File ) | $( $_ . Uri ) " })
}
$sha = [ Security.Cryptography.SHA256 ]:: Create ()
try { ([ BitConverter ]:: ToString ( $sha . ComputeHash ([ Text.Encoding ]:: UTF8 . GetBytes (( $contract | ConvertTo-Json -Depth 5 -Compress ))))). Replace ( '-' , '' ) }
finally { $sha . Dispose () }
}
function Save-OfficeMediaCache {
param ( $Options , $Media , [ string ] $Workspace , [ string ] $CreatedUtc = ([ DateTime ]:: UtcNow . ToString ( 'o' )))
$root = Split-Path -Parent $Workspace
$files = @ ()
foreach ( $name in @ ( 'ODT' , 'odt.exe' ) + @ ( Get-OfficeCompanionDownloads -InstallTeams $Options . InstallTeams | ForEach-Object { $_ . File })) {
foreach ( $file in @ ( Get-OfficeManagedFiles $root ( Join-Path $Workspace $name ))) {
$files += [ pscustomobject ] @ { Path = $file . FullName . Substring ( $Workspace . TrimEnd ( '\' ). Length + 1 ); Length = $file . Length ; Hash =( Get-FileHash -LiteralPath $file . FullName -Algorithm SHA256 -ErrorAction Stop ). Hash }
}
}
[ ordered ] @ { Schema = 1 ; Key =( Get-OfficeMediaCacheKey $Options ); CreatedUtc = $CreatedUtc ; Version = $Media . Version ; Files = $files } |
ConvertTo-Json -Depth 5 | Set-Content -LiteralPath ( Join-Path $Workspace 'media-cache.json' ) -Encoding UTF8 -ErrorAction Stop
}
function Restore-OfficeMediaCache {
param ( $Options , [ string ] $Workspace )
$root = Split-Path -Parent $Workspace
$definitions = Get-OfficeDeploymentDefinitions
$key = Get-OfficeMediaCacheKey $Options
foreach ( $candidate in @ ( Get-ChildItem -LiteralPath $root -Directory -ErrorAction Stop | Where-Object { $_ . Name -match '^[a-f0-9]{32}$' -and $_ . FullName -ne $Workspace } | Sort-Object LastWriteTimeUtc -Descending )) {
$manifestPath = Join-Path $candidate . FullName 'media-cache.json'
if (!( Test-Path -LiteralPath $manifestPath )) { continue }
$inUse = @ ( Get-CimInstance Win32_Process -ErrorAction Stop | Where-Object { $_ . CommandLine -and $_ . CommandLine . IndexOf ( $candidate . FullName , [ StringComparison ]:: OrdinalIgnoreCase ) -ge 0 })
if ( $inUse . Count ) { throw "A previous Office deployment still has active processes using $( $candidate . FullName ) . Wait for them to finish before retrying." }
try {
Assert-OfficeManagedPath $root $manifestPath
$manifest = Get-Content -LiteralPath $manifestPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
$created = [ DateTime ]:: Parse ( $manifest . CreatedUtc ). ToUniversalTime ()
if ( $manifest . Schema -ne 1 -or $manifest . Key -ne $key -or $created -gt [ DateTime ]:: UtcNow -or $created -lt [ DateTime ]:: UtcNow . AddDays (- $definitions . MediaCacheDays )) { continue }
if ( $manifest . Version -notmatch $definitions . OfficeBuildPattern -or ! $manifest . Files . Count ) { throw 'Invalid cache manifest.' }
$names = @ ( 'ODT' , 'odt.exe' ) + @ ( Get-OfficeCompanionDownloads -InstallTeams $Options . InstallTeams | ForEach-Object { $_ . File })
foreach ( $entry in $manifest . Files ) {
if ([ IO.Path ]:: IsPathRooted ( $entry . Path ) -or $entry . Path -match '(^|[\\/])\.\.([\\/]|$)' -or ( $entry . Path -split '[\\/]' )[ 0 ] -notin $names ) { throw 'Invalid cached file path.' }
$path = Join-Path $candidate . FullName $entry . Path
Assert-OfficeManagedPath $candidate . FullName $path
$file = Get-Item -LiteralPath $path -ErrorAction Stop
if ( $file . Length -ne $entry . Length -or ( Get-FileHash -LiteralPath $path -Algorithm SHA256 -ErrorAction Stop ). Hash -ne $entry . Hash ) { throw "Cached file changed: $path " }
}
# Verify every executable we will launch, in addition to the cached hashes.
foreach ( $name in @ ( 'odt.exe' , 'ODT\setup.exe' ) + @ ( Get-OfficeCompanionDownloads -InstallTeams $Options . InstallTeams | ForEach-Object { $_ . File })) {
Assert-OfficeMicrosoftSignature ( Join-Path $candidate . FullName $name )
}
$actualFiles = @ ( foreach ( $name in $names ) { Get-OfficeManagedFiles $root ( Join-Path $candidate . FullName $name ) })
$actualPaths = @ ( $actualFiles | ForEach-Object { $_ . FullName . Substring ( $candidate . FullName . Length + 1 ) } | Sort-Object -Unique )
$expectedPaths = @ ( $manifest . Files . Path | Sort-Object -Unique )
if ( $actualFiles . Count -ne $manifest . Files . Count -or ( Compare-Object $actualPaths $expectedPaths )) { throw 'Cached file inventory changed.' }
} catch {
$null = Write-Output "Ignoring unusable Office cache in $( $candidate . FullName ) : $( $_ . Exception . Message ) "
continue
}
# Transfer rather than duplicate several GB. Each deployment still has a new ID,
# so old per-user completion markers cannot suppress a new cleanup request.
foreach ( $name in $names ) {
$source = Join-Path $candidate . FullName $name ; $destination = Join-Path $Workspace $name
Assert-OfficeManagedPath $root $source ; Assert-OfficeManagedPath $root $destination
if ( Test-Path -LiteralPath $destination ) { throw "Cache destination already exists: $destination " }
Move-Item -LiteralPath $source -Destination $destination -ErrorAction Stop
}
Remove-OfficeManagedItem $root $manifestPath
$null = Write-Output "Reusing verified Office $( $manifest . Version ) media from $( $candidate . FullName ) ."
return $manifest
}
}
2026-10-12 18:31:00 -04:00
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 {
2026-10-21 09:30:15 -04:00
param ([ string ] $Uri , [ string ] $Path , [ int ] $TimeoutSeconds = 0 )
2026-10-12 18:31:00 -04:00
$definitions = Get-OfficeDeploymentDefinitions
2026-10-21 09:30:15 -04:00
if (! $TimeoutSeconds ) { $TimeoutSeconds = $definitions . DownloadTimeoutSeconds }
2026-10-12 18:31:00 -04:00
for ( $attempt = 1 ; $attempt -le $definitions . DownloadAttempts ; $attempt ++) {
try {
$null = Write-Output "Download attempt ${attempt} : $Uri -> $Path "
2026-10-21 09:30:15 -04:00
Invoke-WebRequest -UseBasicParsing -Uri $Uri -OutFile $Path -TimeoutSec $TimeoutSeconds -ErrorAction Stop
2026-10-12 18:31:00 -04:00
if (( Get-Item -LiteralPath $Path -ErrorAction Stop ). Length -eq 0 ) { throw 'Download was empty.' }
2026-10-21 21:01:47 -04:00
if ( $attempt -gt 1 ) { $null = Write-Output "Download recovered on attempt ${attempt} : $Uri -> $Path " }
2026-10-12 18:31:00 -04:00
return
} catch {
2026-10-21 21:01:47 -04:00
$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
2026-10-12 18:31:00 -04:00
}
}
}
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 )
2026-10-21 09:30:15 -04:00
$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 "
$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 "
# 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 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
}
2026-10-12 18:31:00 -04:00
}
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
}
2026-10-21 09:30:15 -04:00
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
}
2026-10-12 18:31:00 -04:00
function Initialize-OfficeMedia {
param ( $Options , [ string ] $Workspace )
$definitions = Get-OfficeDeploymentDefinitions
[ Net.ServicePointManager ]:: SecurityProtocol = [ Net.SecurityProtocolType ]:: Tls12
2026-10-21 09:30:15 -04:00
# Always refresh the small helper from this repository, even when using cached media.
$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.' }
$cached = Restore-OfficeMediaCache $Options $Workspace
if ( $cached ) {
$odtFolder = Join-Path $Workspace 'ODT'
$configPath = Join-Path $Workspace 'install.xml' ; $removalPath = Join-Path $Workspace 'remove.xml'
$config = New-OfficeConfiguration $Options $odtFolder $cached . Version ; $config . Save ( $configPath )
$removal = New-OfficeRemovalConfiguration $Options ; $removal . Save ( $removalPath )
$companions = @ {}
foreach ( $download in ( Get-OfficeCompanionDownloads -InstallTeams $Options . InstallTeams )) { $companions [ $download . Name ] = Join-Path $Workspace $download . File }
# Preserve the original expiry; repeated validation must not keep old media forever.
$cached | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath ( Join-Path $Workspace 'media-cache.json' ) -Encoding UTF8 -ErrorAction Stop
return [ pscustomobject ] @ { Setup =( Join-Path $odtFolder 'setup.exe' ); RemovalConfig = $removalPath ; Config = $configPath ; Helper = $helper ; Version = $cached . Version ; Companions = $companions ; CachedMediaReused = $true }
}
$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 )
2026-10-12 18:31:00 -04:00
$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
2026-10-21 09:30:15 -04:00
$removalPath = Join-Path $Workspace 'remove.xml'
$removal = New-OfficeRemovalConfiguration $Options ; $removal . Save ( $removalPath )
2026-10-12 18:31:00 -04:00
$configPath = Join-Path $Workspace 'install.xml'
$config = New-OfficeConfiguration $Options $odtFolder ; $config . Save ( $configPath )
$null = Write-Output 'Downloading Office installation files before removing installed apps.'
2026-10-21 09:30:15 -04:00
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 )
}
2026-10-12 18:31:00 -04:00
if ( $code -ne 0 ) { throw "Office download failed ( $code ). Existing Office has not been removed." }
$versions = @ ( Get-ChildItem -LiteralPath ( Join-Path $odtFolder 'Office\Data' ) -Directory -ErrorAction Stop | Where-Object { $_ . Name -match $definitions . OfficeBuildPattern })
if ( $versions . Count -ne 1 ) { throw 'Office download did not produce one identifiable build.' }
$arch = if ( $Options . OfficeArchitecture -eq '64' ) { 'x64' } else { 'x86' }
foreach ( $stream in @ ( "stream. $arch .x-none.dat" , "stream. $arch . $( $definitions . Language ) .dat" )) {
if (( Get-Item -LiteralPath ( Join-Path $versions [ 0 ]. FullName $stream ) -ErrorAction Stop ). Length -eq 0 ) { throw "Office payload is empty: $stream " }
}
$config . Configuration . Add . SetAttribute ( 'Version' , $versions [ 0 ]. Name ); $config . Save ( $configPath )
$companions = Initialize-OfficeCompanionMedia $Workspace -InstallTeams $Options . InstallTeams
2026-10-21 09:30:15 -04:00
$media = [ pscustomobject ] @ { Setup = $setup ; RemovalConfig = $removalPath ; Config = $configPath ; Helper = $helper ; Version = $versions [ 0 ]. Name ; Companions = $companions ; CachedMediaReused = $false }
Save-OfficeMediaCache $Options $media $Workspace
$media
2026-10-12 18:31:00 -04:00
}
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.'
2026-10-21 09:30:15 -04:00
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."
}
}
2026-10-12 18:31:00 -04:00
}
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 }
2026-10-21 09:30:15 -04:00
$webViewVersion = Wait-OfficeResult { Get-OfficeMachineWebViewVersion } 'machine WebView2 registration'
2026-10-12 18:31:00 -04:00
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 ) {
2026-10-21 09:30:15 -04:00
$packages = @ ( Wait-OfficeResult { Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_ . DisplayName -eq $app . Package -and $_ . PackageName -like ( '*' + $definitions . AppxPublisherSuffix ) } } " $( $app . Name ) provisioning" )
2026-10-12 18:31:00 -04:00
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 ', '
2026-10-22 00:16:40 -04:00
$null = Write-Output "Verified $( $app . Name ) provisioned package: $( $packages . PackageName -join ', ' ) ."
2026-10-12 18:31:00 -04:00
} else {
2026-10-21 09:30:15 -04:00
$oneDrive = Wait-OfficeResult { Get-OfficeMachineOneDrive } 'per-machine OneDrive registration'
2026-10-12 18:31:00 -04:00
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)'
}
2026-10-21 09:30:15 -04:00
$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 ) " } }
}
2026-10-12 18:31:00 -04:00
}
function Remove-OfficeSuite {
param ( $Media , [ string ] $Workspace )
2026-10-21 09:30:15 -04:00
# 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
2026-10-12 18:31:00 -04:00
}
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 }
}
2026-10-21 09:30:15 -04:00
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."
}
2026-10-12 18:31:00 -04:00
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 })) {
2026-10-21 09:30:15 -04:00
Remove-OfficeAppxEntry $package . PackageName -Provisioned
2026-10-12 18:31:00 -04:00
}
foreach ( $package in @ ( Get-AppxPackage -AllUsers -ErrorAction Stop | Where-Object { $_ . Name -in $names })) {
2026-10-21 09:30:15 -04:00
Remove-OfficeAppxEntry $package . PackageFullName
2026-10-12 18:31:00 -04:00
}
2026-10-21 09:30:15 -04:00
$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.' }
2026-10-12 18:31:00 -04:00
$reboot = $false
2026-10-21 09:30:15 -04:00
foreach ( $entry in @ ( Get-OfficeMachineCompanionEntries )) {
$null = Write-Output "Removing machine companion: $( $entry . DisplayName ) $( $entry . DisplayVersion ) . Registry entry: $( $entry . PSPath ) "
2026-10-12 18:31:00 -04:00
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 )
2026-10-21 09:30:15 -04:00
$code = Invoke-OfficeProcess " $env:WINDIR \System32\msiexec.exe" "/x $( $entry . PSChildName ) /qn /norestart /L+*v `" $prefix .log `" " $prefix
2026-10-12 18:31:00 -04:00
} 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 )." }
}
2026-10-21 09:30:15 -04:00
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." }
}
2026-10-12 18:31:00 -04:00
$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
2026-10-22 00:16:40 -04:00
$deploymentId = Split-Path -Leaf $Workspace ; $tasks = @ (); $registrationFailures = @ ()
2026-10-12 18:31:00 -04:00
foreach ( $profile in $Profiles ) {
$name = "Emberkom-OfficeCleanup- $deploymentId - $( $profile . SID ) "
2026-10-22 00:16:40 -04:00
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
}
2026-10-12 18:31:00 -04:00
$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
2026-10-21 09:30:15 -04:00
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 ) " }
}
2026-10-12 18:31:00 -04:00
else { $pending += $task . SID ; $null = Write-Output "Cleanup pending for $( $task . SID ) ; task $( $task . Name ) runs at their next sign-in." }
}
2026-10-22 00:16:40 -04:00
[ pscustomobject ] @ { PendingUserSids = $pending ; RegistrationFailures = $registrationFailures }
2026-10-12 18:31:00 -04:00
}
function Install-OfficeMedia {
param ( $Options , $Media , [ string ] $Workspace )
2026-10-21 09:30:15 -04:00
$msi = @ ( Get-OfficeSuiteInventory | Where-Object { $_ . WindowsInstaller -eq 1 })
2026-10-12 18:31:00 -04:00
$code = Invoke-OfficeProcess $Media . Setup "/configure `" $( $Media . Config ) `" " ( Join-Path $Workspace 'office-install' )
2026-10-21 09:30:15 -04:00
if ( $code -notin @ ( 0 , 3010 )) { throw "Office installation failed (exit $code ). Media and logs remain in $Workspace . If old Office needs repair, arrange an attended manual scrub: $(( Get-OfficeDeploymentDefinitions ). ManualScrubUrl ) . 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 ) "
}
2026-10-12 18:31:00 -04:00
$platform = if ( $Options . OfficeArchitecture -eq '64' ) { 'x64' } else { 'x86' }
2026-10-21 09:30:15 -04:00
$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
$Options . ProductId -in ( $installed . ProductReleaseIds -split ',' ) -and $installed . Platform -eq $platform -and $installed . VersionToReport -eq $Media . Version
} 'the selected Office product, architecture, and version'
if (! $verified ) { throw 'Setup exited successfully but the installed product, architecture, or version did not match.' }
# 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 }
2026-10-12 18:31:00 -04:00
$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.' }
2026-10-21 09:30:15 -04:00
if ( $Options . DeferReboot -isnot [ bool ]) { throw 'DeferReboot must be a validated Boolean before running the workload.' }
2026-10-12 18:31:00 -04:00
Assert-OfficeDeploymentHost $Options
$mutex = New-Object Threading . Mutex ( $false , 'Global\EmberkomOfficeDeployment' )
$locked = $false
try {
try { $locked = $mutex . WaitOne ( 0 ) } catch [ Threading.AbandonedMutexException ] { $locked = $true }
if (! $locked ) { throw 'Another Emberkom Office deployment is running.' }
$runningApps = @ ( Get-OfficeRunningApps | Select-Object -ExpandProperty ProcessName -Unique )
if ( $runningApps . Count -and $Options . OfficeAppShutdown -eq 'Abort' ) { throw "Apps are running: $( $runningApps -join ', ' ) . Close them or select OfficeAppShutdown=Force for the maintenance window." }
$workspace = New-OfficeWorkspace
2026-10-21 09:30:15 -04:00
$null = Write-Output "Office request: $( $Options . OfficeSubscription ) / $( $Options . ProductId ) , $( $Options . OfficeArchitecture ) -bit, $( $Options . UpdateChannel ) , ValidateBeforeChanges= $( $Options . ValidateBeforeChanges ) , DeferReboot= $( $Options . DeferReboot ) . Workspace: $workspace "
2026-10-12 18:31:00 -04:00
$Options | ConvertTo-Json | Set-Content -LiteralPath ( Join-Path $workspace 'options.json' ) -Encoding UTF8
2026-10-21 09:30:15 -04:00
$root = Split-Path -Parent $workspace
2026-10-12 18:31:00 -04:00
$profiles = @ ( Get-CimInstance Win32_UserProfile -ErrorAction Stop | Where-Object { ! $_ . Special -and $_ . LocalPath })
# Unavailable containers/roaming profiles must not silently disappear from the cleanup report.
foreach ( $profile in $profiles ) {
if (!( Test-Path -LiteralPath ( Join-Path $profile . LocalPath 'NTUSER.DAT' ))) { throw "Profile $( $profile . SID ) is unavailable. Mount its profile/container before deploying." }
}
$media = Initialize-OfficeMedia $Options $workspace
if ( $Options . ValidateBeforeChanges ) {
$existingOffice = @ ( Get-OfficeSuiteInventory | ForEach-Object { $_ . DisplayName })
2026-10-21 09:30:15 -04:00
# This helper is refreshed on every run; validation does not need to retain it.
Remove-OfficeManagedItem $root $media . Helper
$null = Write-Output 'Validation passed. Stopped before closing apps, uninstalling, clearing identities, registering user cleanup tasks, or installing.'
2026-10-12 18:31:00 -04:00
return [ pscustomobject ] @ {
OfficeDeploymentStatus = 'ValidationPassed' ; ExitCode = 0 ; ValidateBeforeChanges = $true
ProductId = $Options . ProductId ; OfficeVersion = $media . Version ; Architecture = $Options . OfficeArchitecture
2026-10-21 09:30:15 -04:00
UpdateChannel = $Options . UpdateChannel ; Company = $Options . Company ; TeamsSelected = $Options . InstallTeams ; OfficeRemovalMethod = 'SilentODT' ; DeferReboot = $Options . DeferReboot
2026-10-12 18:31:00 -04:00
Workspace = $workspace ; ExistingOffice = $existingOffice ; ProfileCount = $profiles . Count ; RunningApps = $runningApps
2026-10-21 09:30:15 -04:00
CachedMediaReused =[ bool ] $media . CachedMediaReused ; MediaCacheDays =( Get-OfficeDeploymentDefinitions ). MediaCacheDays
NextStep = 'Set ValidateBeforeChanges=false to deploy. Matching unexpired media is verified and reused; prerequisites are checked again.'
2026-10-12 18:31:00 -04:00
}
}
Stop-OfficeDeploymentApps $Options
$reboot = Remove-OfficeCompanionApps $workspace
2026-10-21 09:30:15 -04:00
if ( $reboot -and !( Test-OfficeCanDeferRestart $Options 'Companions' )) {
2026-10-12 18:31:00 -04:00
$null = Write-Output 'Companion app removal requires a restart. Restart and rerun; Office installation has not started.'
2026-10-21 09:30:15 -04:00
return [ pscustomobject ] @ { OfficeDeploymentStatus = 'RestartRequiredBeforeInstall' ; ExitCode = 3010 ; RestartRequired = $true ; DeferReboot = $Options . DeferReboot ; RestartStage = 'CompanionRemoval' ; Workspace = $workspace ; PendingUserSids = @ () }
}
$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.'
return [ pscustomobject ] @ { OfficeDeploymentStatus = 'RestartRequiredBeforeInstall' ; ExitCode = 3010 ; RestartRequired = $true ; DeferReboot = $Options . DeferReboot ; RestartStage = 'OfficeRemoval' ; Workspace = $workspace ; PendingUserSids = @ () }
2026-10-12 18:31:00 -04:00
}
foreach ( $profile in $profiles ) { Clear-OfficeProfileIdentity $profile }
2026-10-21 09:30:15 -04:00
$userWorkspace = $workspace
if ( $profiles . Count ) { $userWorkspace = New-OfficeUserWorkspace $media $workspace }
2026-10-22 00:16:40 -04:00
$userCleanup = Start-OfficeUserCleanup $profiles $media $userWorkspace
$pending = @ ( $userCleanup . PendingUserSids )
$registrationFailures = @ ( $userCleanup . RegistrationFailures )
2026-10-21 09:30:15 -04:00
Set-OfficeReinstallPhase $userWorkspace
2026-10-12 18:31:00 -04:00
$code = Install-OfficeMedia $Options $media $workspace
$companions = Install-OfficeCompanionApps $media . Companions $workspace -InstallTeams $Options . InstallTeams
2026-10-21 09:30:15 -04:00
if ( $reboot -or $removalCode -eq 3010 -or $companions . ExitCode -eq 3010 ) { $code = 3010 }
2026-10-22 00:16:40 -04:00
$status = if ( $registrationFailures . Count ) { 'InstalledWithUserCleanupIncomplete' } elseif ( $pending . Count ) { 'InstalledWithUserCleanupPending' } else { 'Installed' }
2026-10-21 09:30:15 -04:00
$null = Write-Output " $status . Office $( $media . Version ) , $( $Options . ProductId ) . No automatic reboot was requested."
2026-10-12 18:31:00 -04:00
$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.'
2026-10-21 09:30:15 -04:00
$cleanupWarnings = @ ()
try {
$cleanupWarnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace -PreviousRoot ( Join-Path $env:ProgramData 'EmberkomOfficeDeployment' )
}
catch { $cleanupWarnings = @ ( $_ . Exception . Message ); Write-Error "Office deployment file cleanup was incomplete: $( $cleanupWarnings [ 0 ]) " -ErrorAction Continue }
if ( $cleanupWarnings . Count ) { $null = Write-Output 'Installation succeeded, but some deployment files remain; see the diagnostic log.' }
2026-10-22 00:16:40 -04:00
[ 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 ; CachedMediaReused =[ bool ] $media . CachedMediaReused ; ArtifactCleanupPending =( $cleanupWarnings . Count -gt 0 ) }
2026-10-12 18:31:00 -04:00
} finally {
if ( $locked ) { $mutex . ReleaseMutex () }
$mutex . Dispose ()
}
}
function New-OfficeNativeCommand {
param ([ hashtable ] $InputValues )
# Reload Tools in the child, preserving the caller's diagnostic log and injected strings.
$context = @ { Inputs = $InputValues ; LogFile =[ string ] $Global:LogFile ; RepositoryRoot =( Get-OfficeDeploymentDefinitions ). RepositoryRoot }
$json64 = [ Convert ]:: ToBase64String ([ Text.Encoding ]:: UTF8 . GetBytes (( $context | ConvertTo-Json -Depth 4 -Compress )))
$command = @'
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$officeContext = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__INPUTS__')) | ConvertFrom-Json
$client = New-Object Net.WebClient
try {
. ([scriptblock]::Create($client.DownloadString($officeContext.RepositoryRoot + '/Tools.ps1')))
if ($officeContext.LogFile) { $Global:LogFile = $officeContext.LogFile }
foreach ($property in $officeContext.Inputs.PSObject.Properties) { Set-Variable -Name $property.Name -Value $property.Value }
$source = $client.DownloadString($officeContext.RepositoryRoot + '/Install-MicrosoftOffice365.ps1')
. ([scriptblock]::Create($source))
throw 'Office workload returned without reporting an exit code.'
} catch {
$message = "Office bootstrap failed: $($_.Exception.Message)"
try { Write-Error $message -ErrorAction Continue }
finally { Microsoft.PowerShell.Utility\Write-Output "ERROR: $message"; exit 1 }
}
finally { $client.Dispose() }
'@
$command . Replace ( '__INPUTS__' , $json64 )
}
function Invoke-OfficeDeploymentEntry {
param ([ hashtable ] $InputValues , [ Parameter ( Mandatory = $true )][ ref ] $ExitCode )
$ErrorActionPreference = 'Stop'
$ExitCode . Value = 1
$options = Get-OfficeDeploymentOptions $InputValues
if (([ Environment ]:: Is64BitOperatingSystem -and ![ Environment ]:: Is64BitProcess ) -or $PSVersionTable . PSEdition -eq 'Core' ) {
$command = New-OfficeNativeCommand $InputValues
# Keep child host/warning messages readable in Syncro instead of emitting CLIXML on stderr.
$command = '$ProgressPreference = ''SilentlyContinue''; & {' + [ Environment ]:: NewLine + $command + [ Environment ]:: NewLine + '} 2>&1 3>&1 4>&1 5>&1 6>&1'
$encoded = [ Convert ]:: ToBase64String ([ Text.Encoding ]:: Unicode . GetBytes ( $command ))
$nativeFolder = if ([ Environment ]:: Is64BitOperatingSystem -and ![ Environment ]:: Is64BitProcess ) { 'Sysnative' } else { 'System32' }
$native = Join-Path $env:WINDIR " $nativeFolder \WindowsPowerShell\v1.0\powershell.exe"
& $native -NoProfile -NonInteractive -ExecutionPolicy Bypass -OutputFormat Text -EncodedCommand $encoded | ForEach-Object { Microsoft . PowerShell . Utility \ Write-Output $_ }
$ExitCode . Value = [ int ] $LASTEXITCODE
if ( $ExitCode . Value -eq 1 ) { Write-Error "Office native-host run failed. See the Syncro output and log: $Global:LogFile " -ErrorAction Continue }
return
}
$null = Write-Output "Office deployment host: Windows PowerShell $( $PSVersionTable . PSVersion ) , $([ IntPtr ]:: Size * 8 ) -bit."
if ( $options . ValidateBeforeChanges ) {
2026-10-21 09:30:15 -04:00
Microsoft . PowerShell . Utility \ Write-Output 'Validation only: checking prerequisites and verifying cached media or staging current installers (several GB). No app shutdown, Office/user cleanup, or installation will run.'
2026-10-12 18:31:00 -04:00
} else {
2026-10-21 09:30:15 -04:00
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.'
2026-10-12 18:31:00 -04:00
}
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*' ) {
2026-10-22 00:16:40 -04:00
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.' }
2026-10-21 09:30:15 -04:00
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.'
2026-10-12 18:31:00 -04:00
}
$ExitCode . Value = [ int ] $deployment [ 0 ]. ExitCode
}
$OfficeInputValues = @ {}
2026-10-21 09:30:15 -04:00
foreach ( $OfficeInputName in @ ( 'OfficeSubscription' , 'OfficeArchitecture' , 'UpdateChannel' , 'OfficeActivation' , 'OfficeAppShutdown' , 'DeferReboot' , 'ValidateBeforeChanges' , 'COMPANY' )) {
2026-10-12 18:31:00 -04:00
$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
}
}