validation check prereqs without staging/caching

This commit is contained in:
2026-10-23 12:23:42 -04:00
parent 08dbb3cdd5
commit f9daec0542
4 changed files with 155 additions and 278 deletions
+82 -163
View File
@@ -83,7 +83,6 @@ function Get-OfficeDeploymentDefinitions {
AppxRemovalAttempts = 3
UserCleanupWaitMinutes = 20
UserCleanupTaskMinutes = 30
MediaCacheDays = 7
# Deployment headroom, not Microsoft's published minimum system requirements.
# Reserve installation/companion space in addition to a fresh media download.
MinimumInstallFreeSpaceGB = 10
@@ -288,7 +287,7 @@ function Assert-OfficeDiskSpace {
$stage = if ($DownloadingMedia) { 'before downloading media' } else { 'after staging, before removal' }
$null = Write-Output "Office disk-space check ${stage}: $drive has $availableGB GB free; deployment requires $requiredGB GB."
if ([long]$disk.FreeSpace -lt $required[$drive]) {
throw "Insufficient disk space on $drive ${stage}: $availableGB GB free; at least $requiredGB GB required. Free space and rerun. Existing apps have not been removed. Staged media remains in $Workspace."
throw "Insufficient disk space on $drive ${stage}: $availableGB GB free; at least $requiredGB GB required. Free space and rerun. Existing apps have not been removed. Deployment media will be cleaned up when installer processes have released it."
}
}
}
@@ -296,52 +295,53 @@ function Assert-OfficeDiskSpace {
function Remove-OfficeStagingFiles {
param([string]$Root, [string]$Workspace)
Assert-OfficeManagedPath $Root $Workspace
$processes = @(Get-CimInstance Win32_Process -ErrorAction Stop)
if (Test-OfficeStagingInUse $Workspace $processes) { throw 'An installer or a process referencing this workspace is still running.' }
# Check every artifact before deleting any part of the payload. The caller holds
# the deployment mutex; these probes also protect against surviving child processes.
foreach ($name in (Get-OfficeStagingNames)) {
foreach ($file in @(Get-OfficeManagedFiles $Root (Join-Path $Workspace $name))) {
$probe = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
$probe.Dispose()
}
}
foreach ($name in (Get-OfficeStagingNames)) { Remove-OfficeManagedItem $Root (Join-Path $Workspace $name) }
}
function Test-OfficeStagingInUse {
param([string]$Workspace, [object[]]$Processes)
# Be conservative even when a child installer no longer names its source folder.
foreach ($process in $Processes) {
if ($process.Name -in @('setup.exe', 'odt.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe')) { return $true }
foreach ($value in @($process.CommandLine, $process.ExecutablePath)) {
if ($value -and $value.IndexOf($Workspace, [StringComparison]::OrdinalIgnoreCase) -ge 0) { return $true }
}
}
return $false
}
function Complete-OfficeDeploymentFiles {
param([string]$Workspace, [string]$UserWorkspace, [string]$PreviousRoot)
param([string]$Workspace, [string]$UserWorkspace)
$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
}
}
# Called from finally on success, failure and restart exits. Keep small logs/XML
# for diagnosis; remove only our disposable media after native processes release it.
try {
$root = Split-Path -Parent $Workspace
Remove-OfficeStagingFiles $root $Workspace
Remove-OfficeManagedItem $root (Join-Path $Workspace 'Office-UserCleanup.ps1')
} catch {
$warnings += "$Workspace : $($_.Exception.Message)"
Write-Error "Deployment media cleanup deferred: $($warnings[-1])" -ErrorAction Continue
}
# Only pass UserWorkspace after a completed installation. Pending helpers survive.
if ($UserWorkspace -and $UserWorkspace -ne $Workspace) {
try {
# 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 }
$processes = @(Get-CimInstance Win32_Process -ErrorAction Stop)
if (!$tasks.Count -and !(Test-OfficeStagingInUse $UserWorkspace $processes)) {
Remove-OfficeManagedItem (Split-Path -Parent $UserWorkspace) $UserWorkspace
}
} catch {
$warnings += "$UserWorkspace : $($_.Exception.Message)"
Write-Error "Could not remove completed user cleanup files: $($warnings[-1])" -ErrorAction Continue
@@ -350,84 +350,21 @@ function Complete-OfficeDeploymentFiles {
return ,$warnings
}
function Get-OfficeMediaCacheKey {
function Resolve-OfficeTargetVersion {
param($Options)
$Options.TargetOfficeVersion = ''
if (!$Options.OfficeFeatureRelease) { return }
$definitions = Get-OfficeDeploymentDefinitions
# Company, activation, app shutdown, and reboot choices affect XML, not the payload.
$contract = [ordered]@{
Schema=2; Product=$Options.ProductId; Architecture=$Options.OfficeArchitecture
Channel=$Options.UpdateChannel; Language=$definitions.Language
TargetVersion=$Options.TargetOfficeVersion
OdtPage=$definitions.OdtPage; ExcludedApps=$definitions.OdtExcludedApps
Downloads=@(Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams | ForEach-Object { "$($_.Name)|$($_.File)|$($_.Uri)" })
}
$contract | ConvertTo-Json -Depth 5 -Compress
}
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 }
}
}
[ordered]@{ Schema=2; 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 2 -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.' }
if ($Options.TargetOfficeVersion -and $manifest.Version -ne $Options.TargetOfficeVersion) { throw 'Cached Office build does not match the Windows 10 target.' }
$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.PSIsContainer -or $file.Length -ne $entry.Length) { throw "Cached file is incomplete: $path" }
}
# Keep publisher checks on executable installers; do not hash the Office payload.
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
# Small metadata only, including in validation. No persistent staging directory.
$historyPath = Join-Path ([IO.Path]::GetTempPath()) ('OfficeReleaseHistory-' + [guid]::NewGuid().ToString('N') + '.html')
try {
Save-OfficeDownload $definitions.OfficeReleaseHistory $historyPath
$Options.TargetOfficeVersion = Get-OfficeBuildFromHistory (Get-Content -LiteralPath $historyPath -Raw -ErrorAction Stop) $Options.UpdateChannel $Options.OfficeFeatureRelease
$null = Write-Output "Windows 10: selected Office $($Options.OfficeFeatureRelease), build $($Options.TargetOfficeVersion), from Microsoft's $($Options.UpdateChannel) release history."
} finally {
if (Test-Path -LiteralPath $historyPath) { Remove-Item -LiteralPath $historyPath -Force -ErrorAction Stop }
}
}
function Assert-OfficeMicrosoftSignature {
param([string]$Path)
$signature = Get-AuthenticodeSignature -LiteralPath $Path -ErrorAction Stop
@@ -593,34 +530,14 @@ function Initialize-OfficeMedia {
param($Options, [string]$Workspace)
$definitions = Get-OfficeDeploymentDefinitions
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$Options.TargetOfficeVersion = ''
if ($Options.OfficeFeatureRelease) {
$historyPath = Join-Path $Workspace 'office-release-history.html'
Save-OfficeDownload $definitions.OfficeReleaseHistory $historyPath
$Options.TargetOfficeVersion = Get-OfficeBuildFromHistory (Get-Content -LiteralPath $historyPath -Raw -ErrorAction Stop) $Options.UpdateChannel $Options.OfficeFeatureRelease
$null = Write-Output "Windows 10: selecting Office $($Options.OfficeFeatureRelease), build $($Options.TargetOfficeVersion), from Microsoft's $($Options.UpdateChannel) release history."
} else {
$null = Write-Output "ODT will select the latest available Office version in $($Options.UpdateChannel); no version is specified."
}
# Always refresh the small helper from this repository, even when using cached media.
if ($Options.OfficeFeatureRelease -and !$Options.TargetOfficeVersion) { Resolve-OfficeTargetVersion $Options }
Assert-OfficeDiskSpace -Workspace $Workspace -DownloadingMedia
# Download only in the install workflow; no persistent cache or cross-run reuse.
$helper = Join-Path $Workspace 'Office-UserCleanup.ps1'
Save-OfficeDownload "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1" $helper
$tokens = $null; $errors = $null
$null = [Management.Automation.Language.Parser]::ParseFile($helper, [ref]$tokens, [ref]$errors)
if ($errors.Count -or !(Select-String -LiteralPath $helper -SimpleMatch $definitions.HelperVersion -Quiet)) { throw 'Office user cleanup helper is invalid; publish it with this installer.' }
$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 $Options.TargetOfficeVersion; $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 }
}
Assert-OfficeDiskSpace -Workspace $Workspace -DownloadingMedia
$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)
@@ -653,8 +570,7 @@ function Initialize-OfficeMedia {
if ((Get-Item -LiteralPath (Join-Path $versions[0].FullName $stream) -ErrorAction Stop).Length -eq 0) { throw "Office payload is empty: $stream" }
}
$companions = Initialize-OfficeCompanionMedia $Workspace -InstallTeams $Options.InstallTeams
$media = [pscustomobject]@{ Setup = $setup; RemovalConfig = $removalPath; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions; CachedMediaReused=$false }
Save-OfficeMediaCache $Options $media $Workspace
$media = [pscustomobject]@{ Setup = $setup; RemovalConfig = $removalPath; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions }
$media
}
@@ -1060,7 +976,7 @@ function Install-OfficeMedia {
param($Options, $Media, [string]$Workspace)
$msi = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 })
$code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.Config)`"" (Join-Path $Workspace 'office-install')
if ($code -notin @(0, 3010)) { throw "Office installation failed (exit $code). Media and logs remain in $Workspace. Review the Native Office log/detail entries in the diagnostic log; Click-to-Run writes its underlying errors to the execution account's temp folder or Windows\Temp. The exit code alone does not identify the cause. No interactive scrubber was launched." }
if ($code -notin @(0, 3010)) { throw "Office installation failed (exit $code). Diagnostic logs remain in $Workspace; disposable media is cleaned up after installer processes finish. Review the Native Office log/detail entries in the diagnostic log; Click-to-Run writes its underlying errors to the execution account's temp folder or Windows\Temp. The exit code alone does not identify the cause. No interactive scrubber was launched." }
$msiRemoved = Wait-OfficeResult { @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 }).Count -eq 0 } 'legacy MSI Office removal by ODT'
if (!$msiRemoved) {
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 })
@@ -1097,48 +1013,49 @@ function Invoke-OfficeDeployment {
Assert-OfficeDeploymentHost $Options
$mutex = New-Object Threading.Mutex($false, 'Global\EmberkomOfficeDeployment')
$locked = $false
$workspace = $null; $userWorkspace = $null; $receipt = $null; $completed = $false
try {
try { $locked = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $locked = $true }
if (!$locked) { throw 'Another Emberkom Office deployment is running.' }
$runningApps = @(Get-OfficeRunningApps | Select-Object -ExpandProperty ProcessName -Unique)
if ($runningApps.Count -and $Options.OfficeAppShutdown -eq 'Abort') { throw "Apps are running: $($runningApps -join ', '). Close them or select OfficeAppShutdown=Force for the maintenance window." }
$workspace = New-OfficeWorkspace
$null = Write-Output "Office request: $($Options.OfficeSubscription) / $($Options.ProductId), $($Options.OfficeArchitecture)-bit, $($Options.UpdateChannel), ValidateBeforeChanges=$($Options.ValidateBeforeChanges), DeferReboot=$($Options.DeferReboot). Workspace: $workspace"
$Options | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $workspace 'options.json') -Encoding UTF8
$root = Split-Path -Parent $workspace
$null = Write-Output "Office request: $($Options.OfficeSubscription) / $($Options.ProductId), $($Options.OfficeArchitecture)-bit, $($Options.UpdateChannel), ValidateBeforeChanges=$($Options.ValidateBeforeChanges), DeferReboot=$($Options.DeferReboot)."
$profiles = @(Get-CimInstance Win32_UserProfile -ErrorAction Stop | Where-Object { !$_.Special -and $_.LocalPath })
# Unavailable containers/roaming profiles must not silently disappear from the cleanup report.
foreach ($profile in $profiles) {
if (!(Test-Path -LiteralPath (Join-Path $profile.LocalPath 'NTUSER.DAT'))) { throw "Profile $($profile.SID) is unavailable. Mount its profile/container before deploying." }
}
$media = Initialize-OfficeMedia $Options $workspace
# Also check cache hits: a successful download does not prove enough space
# remains to expand Office and install the selected companion apps.
Assert-OfficeDiskSpace -Workspace $workspace
Resolve-OfficeTargetVersion $Options
$stagingRoot = Join-Path ([IO.Path]::GetTempPath()) 'EmberkomOfficeDeployment'
Assert-OfficeDiskSpace -Workspace $stagingRoot -DownloadingMedia
if ($Options.ValidateBeforeChanges) {
$existingOffice = @(Get-OfficeSuiteInventory | ForEach-Object { $_.DisplayName })
# 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.'
$null = Write-Output 'Validation passed. No installation media downloaded or staging workspace created. Installation will repeat prerequisites and verify downloads before removal.'
return [pscustomobject]@{
OfficeDeploymentStatus='ValidationPassed'; ExitCode=0; ValidateBeforeChanges=$true
ProductId=$Options.ProductId; OfficeVersion=$media.Version; Architecture=$Options.OfficeArchitecture
ProductId=$Options.ProductId; OfficeVersion=$Options.TargetOfficeVersion; Architecture=$Options.OfficeArchitecture
UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams; OfficeRemovalMethod='SilentODT'; DeferReboot=$Options.DeferReboot
Workspace=$workspace; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps
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.'
Workspace=$null; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps; MediaDownloaded=$false
NextStep='Set ValidateBeforeChanges=false to download, verify, deploy, and clean up installation media. Prerequisites are checked again.'
}
}
$workspace = New-OfficeWorkspace
$null = Write-Output "Temporary deployment workspace: $workspace"
$Options | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $workspace 'options.json') -Encoding UTF8
$media = Initialize-OfficeMedia $Options $workspace
Assert-OfficeDiskSpace -Workspace $workspace
Stop-OfficeDeploymentApps $Options
$reboot = Remove-OfficeCompanionApps $workspace
if ($reboot -and !(Test-OfficeCanDeferRestart $Options 'Companions')) {
$null = Write-Output 'Companion app removal requires a restart. Restart and rerun; Office installation has not started.'
return [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'CompanionRemoval'; Workspace = $workspace; PendingUserSids = @() }
$receipt = [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'CompanionRemoval'; Workspace = $workspace; PendingUserSids = @(); ArtifactCleanupPending=$false }
return $receipt
}
$removalCode = Remove-OfficeSuite $media $workspace
if ($removalCode -eq 3010 -and !(Test-OfficeCanDeferRestart $Options 'Office')) {
$null = Write-Output 'Office removal requires a restart. Restart and rerun; replacement installation has not started.'
return [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @() }
$receipt = [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @(); ArtifactCleanupPending=$false }
return $receipt
}
foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile }
$userWorkspace = $workspace
@@ -1155,14 +1072,16 @@ function Invoke-OfficeDeployment {
$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.'
$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.' }
[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) }
$completed = $true
$receipt = [pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if (($pending.Count -or $registrationFailures.Count) -and $code -eq 0) { 2 } else { $code }); RestartRequired=($code -eq 3010); DeferReboot=$Options.DeferReboot; ValidateBeforeChanges=$false; Workspace = $workspace; UserCleanupWorkspace=$(if ($profiles.Count) { $userWorkspace } else { $null }); PendingUserSids = $pending; UserCleanupRegistrationFailures = $registrationFailures; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version; MediaDownloaded=$true; ArtifactCleanupPending=$false }
return $receipt
} finally {
if ($workspace) {
try { $cleanupWarnings = Complete-OfficeDeploymentFiles $workspace $(if ($completed) { $userWorkspace } else { $null }) }
catch { $cleanupWarnings = @($_.Exception.Message); Write-Error "Office media cleanup failed: $($cleanupWarnings[0])" -ErrorAction Continue }
if ($receipt) { $receipt.ArtifactCleanupPending = $cleanupWarnings.Count -gt 0 }
if ($cleanupWarnings.Count) { $null = Write-Output 'Some deployment media remains; review the log and use OfficeStaging cleanup after installer processes finish.' }
}
if ($locked) { $mutex.ReleaseMutex() }
$mutex.Dispose()
}
@@ -1215,7 +1134,7 @@ 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 verifying cached media or staging current installers (several GB). No app shutdown, Office/user cleanup, or installation will run.'
Microsoft.PowerShell.Utility\Write-Output 'Validation only: checking prerequisites and optional release metadata. No installation media downloads, staging, app shutdown, Office/user cleanup, or installation will run.'
} else {
Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: validating and staging media, then silently removing Office with ODT and reinstalling Office and the selected companion apps.'
}