update M365 deployment script to try not to depend on previous deployments

This commit is contained in:
2026-10-29 14:29:37 -04:00
parent e2163a6158
commit 3e24920646
7 changed files with 465 additions and 85 deletions
+203 -38
View File
@@ -32,7 +32,7 @@ function Get-OfficeDeploymentDefinitions {
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'
HelperVersion = 'EmberkomOfficeUserCleanup-v5'
Language = 'en-us'
OfficeBuildPattern = '^16\.0\.\d+\.\d+$'
OdtExcludedApps = @('Groove', 'OneDrive', 'Lync', 'Teams', 'OutlookForWindows')
@@ -61,6 +61,11 @@ function Get-OfficeDeploymentDefinitions {
MonthlyEnterprise = 'monthly-enterprise-channel'
SemiAnnual = 'semi-annual-enterprise-channel'
}
OfficeCdnChannels = @{
Current = '492350f6-3a01-4f97-b9c0-c7c6ddf67d60'
MonthlyEnterprise = '55336b82-a18d-4dd6-b5f6-9e5095c314a6'
SemiAnnual = '7ffbc6bf-bc32-4f92-8982-f9dd17fd3114'
}
TeamsUnsupportedWindows10Editions = @('EnterpriseS', 'EnterpriseSN', 'IoTEnterpriseS')
# Teams.exe is classic, msteams.exe is the older personal/Windows Chat client,
# and ms-teams.exe is the current client. Check all three before removal.
@@ -192,6 +197,7 @@ function New-OfficeWorkspace {
)
# Executable content must never be writable by a standard user.
# Default to the execution account's temp location (SYSTEM under Syncro).
Assert-OfficeManagedPath $root (Join-Path $root $DeploymentId)
$null = New-Item -ItemType Directory -Path $root -Force -ErrorAction Stop
for ($item = Get-Item -LiteralPath $root -Force; $null -ne $item; $item = $item.Parent) {
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Deployment path traverses a reparse point: $($item.FullName)" }
@@ -213,15 +219,60 @@ function New-OfficeWorkspace {
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.
# Persist only synchronization state for deferred tasks. They fetch code live;
# no downloaded helper or installation payload survives in ProgramData.
$path = New-OfficeWorkspace -Root (Join-Path $env:ProgramData 'EmberkomOfficeDeployment') -DeploymentId (Split-Path -Leaf $Workspace)
$helper = Join-Path $path 'Office-UserCleanup.ps1'
Copy-Item -LiteralPath $Media.Helper -Destination $helper -ErrorAction Stop
$Media.Helper = $helper
$path
}
function Assert-OfficeWritablePath {
param([string]$Path)
$target = [IO.Path]::GetFullPath($Path)
# Probe the closest existing parent without creating the intended directory.
$parent = $target
while (!(Test-Path -LiteralPath $parent)) {
$parent = Split-Path -Parent $parent
if (!$parent) { throw "No existing parent for deployment path: $target" }
}
Assert-OfficeManagedPath $parent (Join-Path $parent 'office-write-probe')
if (!(Test-Path -LiteralPath $parent -PathType Container)) { throw "Deployment parent is not a directory: $parent" }
$probePath = Join-Path $parent ('OfficeWriteProbe-' + [guid]::NewGuid().ToString('N') + '.tmp')
$probe = $null
try {
$probe = [IO.FileStream]::new($probePath, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None, 1, [IO.FileOptions]::DeleteOnClose)
} catch { throw "Deployment path is not writable: $target (tested $parent). $($_.Exception.Message)" }
finally { if ($probe) { $probe.Dispose() } }
$null = Write-Output "Writable path verified: $target (tested existing directory $parent)."
[pscustomobject]@{ Path=$target; TestedDirectory=$parent }
}
function Test-OfficeDownloadLinks {
param($Options)
$definitions = Get-OfficeDeploymentDefinitions
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$links = @($definitions.OdtPage, "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1")
if ($Options.OfficeFeatureRelease) { $links += $definitions.OfficeReleaseHistory }
$channel = $definitions.OfficeCdnChannels[$Options.UpdateChannel]
$links += "https://officecdn.microsoft.com/pr/$channel/Office/Data/v$($Options.OfficeArchitecture).cab"
foreach ($name in @('WebView2', 'NewOutlook', 'OneDrive', 'Teams')) {
if ($name -eq 'Teams' -and !$Options.InstallTeams) { continue }
$installer = $definitions.CompanionInstallers[$name]
if ($name -eq 'OneDrive') {
$arch = if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64' -or $env:PROCESSOR_ARCHITEW6432 -eq 'ARM64') { 'ARM64' } elseif ([Environment]::Is64BitOperatingSystem) { 'x64' } else { 'x86' }
$links += $installer.Uris[$arch]
} else { $links += $installer.Uri }
}
foreach ($uri in $links) {
# HEAD follows redirects but never requests a body or writes a download.
# A server that refuses HEAD fails assessment; do not fall back to GET.
try { $response = Invoke-WebRequest -UseBasicParsing -Method Head -Uri $uri -MaximumRedirection 10 -TimeoutSec $definitions.OdtPageTimeoutSeconds -ErrorAction Stop }
catch { throw "HTTP HEAD check failed for $uri. $($_.Exception.Message)" }
if ([int]$response.StatusCode -ne 200) { throw "HTTP HEAD check for $uri returned $($response.StatusCode); expected 200." }
$null = Write-Output "HTTP HEAD 200: $uri"
[pscustomobject]@{ Uri=$uri; StatusCode=200; Method='HEAD' }
}
}
function Assert-OfficeManagedPath {
param([string]$Root, [string]$Path)
$base = [IO.Path]::GetFullPath($Root).TrimEnd('\')
@@ -256,12 +307,6 @@ function Remove-OfficeManagedItem {
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,
@@ -299,13 +344,62 @@ function Remove-OfficeStagingFiles {
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()
$files = @(Get-OfficeManagedFiles $Root $Workspace | Where-Object { $_.Extension -notin @('.log', '.etl') })
foreach ($file in $files) {
$probe = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
$probe.Dispose()
}
foreach ($file in $files) { Remove-OfficeManagedItem $Root $file.FullName }
# Preserve nested logs and their parents, but discard empty payload folders.
foreach ($folder in @(Get-ChildItem -LiteralPath $Workspace -Directory -Recurse -Force -ErrorAction Stop | Sort-Object { $_.FullName.Length } -Descending)) {
Assert-OfficeManagedPath $Root $folder.FullName
if (!@(Get-ChildItem -LiteralPath $folder.FullName -Force -ErrorAction Stop).Count) { Remove-Item -LiteralPath $folder.FullName -Force -ErrorAction Stop }
}
}
function Get-OfficeDeploymentRoots {
$parents = @([IO.Path]::GetTempPath(), (Join-Path $env:WINDIR 'Temp'), (Join-Path $env:WINDIR 'SystemTemp'), $env:ProgramData)
foreach ($profile in @(Get-CimInstance Win32_UserProfile -ErrorAction Stop)) {
if ($profile.LocalPath) { $parents += Join-Path $profile.LocalPath 'AppData\Local\Temp' }
}
@($parents | Where-Object { $_ } | ForEach-Object { [IO.Path]::GetFullPath((Join-Path $_ 'EmberkomOfficeDeployment')).TrimEnd('\') } | Sort-Object -Unique)
}
function Clear-OfficePreviousDeploymentFiles {
# The deployment mutex is held by the caller. Never import options, XML or media
# from these folders; the reserved root and GUID identify our prior workspaces.
$roots = @(Get-OfficeDeploymentRoots)
$processes = @(Get-CimInstance Win32_Process -ErrorAction Stop)
foreach ($root in $roots) {
if (Test-OfficeStagingInUse $root $processes) { throw "A surviving installer is running. Stop the previous deployment before removing old artifacts in $root." }
Assert-OfficeManagedPath $root (Join-Path $root 'path-check')
}
$tasks = @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -match '^Emberkom-OfficeCleanup-[a-f0-9]{32}-S-1-[\d-]+$' })
if (@($tasks | Where-Object { $_.State -in @('Running', 'Queued') }).Count) { throw 'Previous Office user cleanup is still running. Wait for it to finish before redeploying.' }
foreach ($task in $tasks) {
$null = Disable-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -ErrorAction Stop
if ((Get-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -ErrorAction Stop).State -in @('Running', 'Queued')) { throw "Previous user cleanup started during preparation: $($task.TaskName)." }
Unregister-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -Confirm:$false -ErrorAction Stop
$null = Write-Output "Retired previous user cleanup task; this deployment will schedule fresh cleanup: $($task.TaskName)"
}
foreach ($root in $roots) {
# Older validation runs wrote release metadata beside the staging root.
# New runs keep it inside their GUID workspace, including partial downloads.
$parent = Split-Path -Parent $root
if (Test-Path -LiteralPath $parent -PathType Container) {
foreach ($file in @(Get-ChildItem -LiteralPath $parent -File -Filter 'OfficeReleaseHistory-*.html' -ErrorAction Stop | Where-Object { $_.Name -match '^OfficeReleaseHistory-[a-f0-9]{32}\.html$' })) {
Assert-OfficeManagedPath $parent $file.FullName
$probe = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
$probe.Dispose()
Remove-OfficeManagedItem $parent $file.FullName
}
}
if (!(Test-Path -LiteralPath $root)) { continue }
foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -Force -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' })) {
Remove-OfficeStagingFiles $root $folder.FullName
if (!@(Get-ChildItem -LiteralPath $folder.FullName -Force -ErrorAction Stop).Count) { Remove-OfficeManagedItem $root $folder.FullName }
}
}
foreach ($name in (Get-OfficeStagingNames)) { Remove-OfficeManagedItem $Root (Join-Path $Workspace $name) }
}
function Test-OfficeStagingInUse {
@@ -313,6 +407,7 @@ function Test-OfficeStagingInUse {
# 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 }
if ($process.Name -eq 'OfficeClickToRun.exe' -and $process.CommandLine -notmatch '(?i)\s/(service|user)\s*$') { return $true }
foreach ($value in @($process.CommandLine, $process.ExecutablePath)) {
if ($value -and $value.IndexOf($Workspace, [StringComparison]::OrdinalIgnoreCase) -ge 0) { return $true }
}
@@ -323,17 +418,16 @@ function Test-OfficeStagingInUse {
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.
# Called from finally on success, failure and restart exits. Only logs remain
# in the download workspace after native processes release it.
try {
$root = Split-Path -Parent $Workspace
Remove-OfficeStagingFiles $root $Workspace
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.
# Pending tasks need only their lock and phase marker, not downloaded code.
if ($UserWorkspace -and $UserWorkspace -ne $Workspace) {
try {
$id = Split-Path -Leaf $UserWorkspace
@@ -351,12 +445,13 @@ function Complete-OfficeDeploymentFiles {
}
function Resolve-OfficeTargetVersion {
param($Options)
param($Options, [Parameter(Mandatory=$true)][string]$Workspace)
$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')
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Deployment only. Assessment checks HEAD without resolving/downloading metadata.
$historyPath = Join-Path $Workspace 'office-release-history.html'
try {
Save-OfficeDownload $definitions.OfficeReleaseHistory $historyPath
$Options.TargetOfficeVersion = Get-OfficeBuildFromHistory (Get-Content -LiteralPath $historyPath -Raw -ErrorAction Stop) $Options.UpdateChannel $Options.OfficeFeatureRelease
@@ -530,7 +625,7 @@ 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 }
if ($Options.OfficeFeatureRelease -and !$Options.TargetOfficeVersion) { Resolve-OfficeTargetVersion $Options $Workspace }
Assert-OfficeDiskSpace -Workspace $Workspace -DownloadingMedia
# Download only in the install workflow; no persistent cache or cross-run reuse.
$helper = Join-Path $Workspace 'Office-UserCleanup.ps1'
@@ -553,6 +648,8 @@ function Initialize-OfficeMedia {
$removal = New-OfficeRemovalConfiguration $Options; $removal.Save($removalPath)
$configPath = Join-Path $Workspace 'install.xml'
$config = New-OfficeConfiguration $Options $odtFolder $Options.TargetOfficeVersion; $config.Save($configPath)
$null = Write-Output "Office removal configuration: $($removal.OuterXml)"
$null = Write-Output "Office installation configuration: $($config.OuterXml)"
$null = Write-Output 'Downloading Office installation files before removing installed apps.'
for ($attempt = 1; $attempt -le $definitions.DownloadAttempts; $attempt++) {
$prefix = if ($attempt -eq 1) { 'office-download' } else { "office-download.retry-$attempt" }
@@ -711,6 +808,41 @@ function Get-OfficeSuiteInventory {
}
}
function Get-OfficeClickToRunState {
# Finished-product inventory misses interrupted installations. Read servicing
# state as evidence only; ODT, not registry deletion, must remove the old setup.
$root = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun'
$present = Test-Path -LiteralPath $root -ErrorAction Stop
$sources = @(); $working = @()
if ($present) {
$keys = @((Get-Item -LiteralPath $root -ErrorAction Stop)) + @(Get-ChildItem -LiteralPath $root -Recurse -ErrorAction Stop)
foreach ($key in $keys) {
$values = Get-ItemProperty -LiteralPath $key.PSPath -ErrorAction Stop
foreach ($property in $values.PSObject.Properties) {
if ($property.Name -like 'PS*') { continue }
foreach ($value in @($property.Value)) {
if ($value -isnot [string] -or !$value.Trim()) { continue }
if ($value -match '(?i)EmberkomOfficeDeployment[\\/]') { $sources += "$($key.Name) : $($property.Name) = $value" }
if ($property.Name -match '^WorkingConfig(uration)?$' -and $value.Trim('{}') -ne '00000000-0000-0000-0000-000000000000') { $working += $value }
}
}
}
}
$service = Get-Service -Name ClickToRunSvc -ErrorAction SilentlyContinue
[pscustomobject]@{ Present=($present -or $null -ne $service); SourceReferences=$sources; WorkingConfiguration=$working }
}
function Assert-OfficeFreshInstallState {
$cleared = Wait-OfficeResult {
$state = Get-OfficeClickToRunState
!$state.SourceReferences.Count -and !$state.WorkingConfiguration.Count
} 'removal of previous Click-to-Run working configuration and deployment source references'
if (!$cleared) {
$state = Get-OfficeClickToRunState
throw "Click-to-Run still retains previous deployment state after ODT removal. Installation stopped to prevent reuse of old content. Working configuration: $($state.WorkingConfiguration -join ', '). Source references: $($state.SourceReferences -join '; '). Arrange an attended Office repair/scrub: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)"
}
}
function Remove-OfficeSuite {
param($Media, [string]$Workspace)
# Get Help can create an interactive elevated child despite a hidden SYSTEM parent.
@@ -718,12 +850,13 @@ function Remove-OfficeSuite {
$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.'
$state = Get-OfficeClickToRunState
if (!@($existing | Where-Object { $_.WindowsInstaller -ne 1 }).Count -and !$state.Present) {
$null = Write-Output 'No Click-to-Run products, service or servicing state detected; skipping the separate ODT removal pass.'
return 0
}
if (!$Media.RemovalConfig -or !(Test-Path -LiteralPath $Media.RemovalConfig -PathType Leaf)) { throw 'The staged silent Office removal configuration is missing.' }
$null = Write-Output 'Silently removing Click-to-Run Office, including Visio and Project, with ODT.'
$null = Write-Output 'Silently removing Click-to-Run Office, including incomplete deployments, 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" }
@@ -927,6 +1060,25 @@ function Clear-OfficeProfileIdentity {
}
}
function New-OfficeUserCleanupCommand {
param([ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId)
$definitions = Get-OfficeDeploymentDefinitions
$uri = "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1".Replace("'", "''")
$version = $definitions.HelperVersion.Replace("'", "''")
$command = @'
$ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
try {
$client = New-Object Net.WebClient
try { $source = $client.DownloadString('__URI__') } finally { $client.Dispose() }
if (!$source.Contains('__VERSION__')) { throw 'Office user cleanup helper version does not match its deployment.' }
& ([scriptblock]::Create($source)) -DeploymentId '__ID__'
} catch { Write-Error $_ -ErrorAction Continue; exit 1 }
'@
$command = $command.Replace('__URI__', $uri).Replace('__VERSION__', $version).Replace('__ID__', $DeploymentId)
[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
}
function Start-OfficeUserCleanup {
param([object[]]$Profiles, $Media, [string]$Workspace)
$definitions = Get-OfficeDeploymentDefinitions
@@ -934,7 +1086,8 @@ function Start-OfficeUserCleanup {
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
$command = New-OfficeUserCleanupCommand $deploymentId
$action = New-ScheduledTaskAction -Execute "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand $command" -ErrorAction Stop
$principal = New-ScheduledTaskPrincipal -UserId $profile.SID -LogonType Interactive -RunLevel Limited -ErrorAction Stop
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $profile.SID -ErrorAction Stop
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes $definitions.UserCleanupTaskMinutes) -MultipleInstances IgnoreNew -ErrorAction Stop
@@ -988,7 +1141,7 @@ function Install-OfficeMedia {
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.
# Unpinned ODT can install a newer build than this run's earlier download.
# Windows 10 must still match its explicitly selected compatible build.
if ($Options.TargetOfficeVersion) {
if ($installed.VersionToReport -ne $Options.TargetOfficeVersion) { return $false }
@@ -1025,23 +1178,31 @@ function Invoke-OfficeDeployment {
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
$paths = @($stagingRoot, (Join-Path $env:ProgramData 'EmberkomOfficeDeployment'), $env:ProgramFiles, ${env:ProgramFiles(x86)})
$writablePaths = @($paths | Where-Object { $_ } | Select-Object -Unique | ForEach-Object { Assert-OfficeWritablePath $_ })
if ($Options.ValidateBeforeChanges) {
Assert-OfficeDiskSpace -Workspace $stagingRoot -DownloadingMedia
$downloadChecks = @(Test-OfficeDownloadLinks $Options)
$existingOffice = @(Get-OfficeSuiteInventory | ForEach-Object { $_.DisplayName })
$null = Write-Output 'Validation passed. No installation media downloaded or staging workspace created. Installation will repeat prerequisites and verify downloads before removal.'
$state = Get-OfficeClickToRunState
$null = Write-Output 'Assessment passed. HTTP HEAD checks returned 200; no response bodies downloaded or deployment directory created. Exact ODT package and Office build resolution/signature verification occur only during deployment.'
return [pscustomobject]@{
OfficeDeploymentStatus='ValidationPassed'; ExitCode=0; ValidateBeforeChanges=$true
ProductId=$Options.ProductId; OfficeVersion=$Options.TargetOfficeVersion; Architecture=$Options.OfficeArchitecture
UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams; OfficeRemovalMethod='SilentODT'; DeferReboot=$Options.DeferReboot
Workspace=$null; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps; MediaDownloaded=$false
WritablePaths=$writablePaths; DownloadChecks=$downloadChecks; ClickToRunState=$state; OfficeFeatureRelease=$Options.OfficeFeatureRelease; MetadataResolved=$false
NextStep='Set ValidateBeforeChanges=false to download, verify, deploy, and clean up installation media. Prerequisites are checked again.'
}
}
Clear-OfficePreviousDeploymentFiles
Assert-OfficeDiskSpace -Workspace $stagingRoot -DownloadingMedia
$workspace = New-OfficeWorkspace
$null = Write-Output "Temporary deployment workspace: $workspace"
$Options | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $workspace 'options.json') -Encoding UTF8
# Keep the request in a diagnostic log; XML and options are never reused.
$Options | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $workspace 'deployment-options.log') -Encoding UTF8
Resolve-OfficeTargetVersion $Options $workspace
$media = Initialize-OfficeMedia $Options $workspace
Assert-OfficeDiskSpace -Workspace $workspace
Stop-OfficeDeploymentApps $Options
@@ -1057,6 +1218,7 @@ function Invoke-OfficeDeployment {
$receipt = [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @(); ArtifactCleanupPending=$false }
return $receipt
}
Assert-OfficeFreshInstallState
foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile }
$userWorkspace = $workspace
if ($profiles.Count) { $userWorkspace = New-OfficeUserWorkspace $media $workspace }
@@ -1079,8 +1241,11 @@ function Invoke-OfficeDeployment {
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 ($receipt) {
$receipt.ArtifactCleanupPending = $cleanupWarnings.Count -gt 0
if ($cleanupWarnings.Count -and $receipt.ExitCode -eq 0) { $receipt.ExitCode = 2; $receipt.OfficeDeploymentStatus = 'InstalledWithArtifactCleanupPending' }
}
if ($cleanupWarnings.Count) { $null = Write-Output 'Some deployment artifacts could not be removed safely. Stop surviving installers before rerunning; the next deployment must clean prior artifacts before downloading fresh media.' }
}
if ($locked) { $mutex.ReleaseMutex() }
$mutex.Dispose()
@@ -1134,9 +1299,9 @@ function Invoke-OfficeDeploymentEntry {
}
$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.'
Microsoft.PowerShell.Utility\Write-Output 'Validation only: checking prerequisites, writable paths and HTTP HEAD 200 responses. No metadata or payload downloads, deployment directory, artifact cleanup, app shutdown, or installation will run.'
} else {
Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: validating and staging media, then silently removing Office with ODT and reinstalling Office and the selected companion apps.'
Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: clearing prior artifacts, downloading fresh media, then silently removing Office with ODT and installing the selected apps. Download workspaces retain only logs after cleanup.'
}
Microsoft.PowerShell.Utility\Write-Output "Diagnostic log: $Global:LogFile"
$results = @(Invoke-OfficeDeployment -Options $options)