added a few fixes
This commit is contained in:
+479
-90
@@ -31,13 +31,8 @@ function Get-OfficeDeploymentDefinitions {
|
||||
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'
|
||||
GetHelpUrl = 'https://aka.ms/SaRA_EnterpriseVersionFiles'
|
||||
GetHelpExecutable = 'GetHelpCmd.exe'
|
||||
ScrubArguments = '-S OfficeScrubScenario -AcceptEula -OfficeVersion All'
|
||||
ScrubScenarioPattern = '(?m)^\s*(\d{2}):'
|
||||
ScrubScenarioSuccess = @('00', '66', '68')
|
||||
ScrubExitSuccess = @(0, 66, 68)
|
||||
HelperVersion = 'EmberkomOfficeUserCleanup-v2'
|
||||
ManualScrubUrl = 'https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall'
|
||||
HelperVersion = 'EmberkomOfficeUserCleanup-v4'
|
||||
Language = 'en-us'
|
||||
OfficeBuildPattern = '^16\.0\.\d+\.\d+$'
|
||||
OdtExcludedApps = @('Groove', 'OneDrive', 'Lync', 'Teams', 'OutlookForWindows')
|
||||
@@ -68,8 +63,16 @@ function Get-OfficeDeploymentDefinitions {
|
||||
DownloadTimeoutSeconds = 300
|
||||
DownloadRetrySeconds = 3
|
||||
OdtPageTimeoutSeconds = 120
|
||||
UserCleanupWaitMinutes = 5
|
||||
UserCleanupTaskMinutes = 15
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,6 +84,9 @@ function Get-OfficeDeploymentOptions {
|
||||
[string]$validate = $InputValues.ValidateBeforeChanges
|
||||
if ([string]::IsNullOrWhiteSpace($validate)) { $validate = 'true' }
|
||||
$validateOnly = ConvertTo-RmmBoolean -Value $validate -VariableName 'ValidateBeforeChanges'
|
||||
[string]$defer = $InputValues.DeferReboot
|
||||
if ([string]::IsNullOrWhiteSpace($defer)) { $defer = 'true' }
|
||||
$deferReboot = ConvertTo-RmmBoolean -Value $defer -VariableName 'DeferReboot'
|
||||
[string]$subscription = $InputValues.OfficeSubscription
|
||||
$subscription = $subscription.Trim()
|
||||
# Accept previously documented individual names for existing saved RMM selections.
|
||||
@@ -94,7 +100,7 @@ function Get-OfficeDeploymentOptions {
|
||||
[string]$company = $InputValues.COMPANY
|
||||
$company = $company.Trim()
|
||||
if ($company -eq 'None') { $company = '' }
|
||||
$options = @{ OfficeSubscription = $subscription; ProductId = $plans[$subscription]; Company = $company; ValidateBeforeChanges = $validateOnly }
|
||||
$options = @{ OfficeSubscription = $subscription; ProductId = $plans[$subscription]; Company = $company; ValidateBeforeChanges = $validateOnly; DeferReboot = $deferReboot }
|
||||
# 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) {
|
||||
@@ -134,8 +140,12 @@ function Assert-OfficeCompanionPlatform {
|
||||
}
|
||||
|
||||
function New-OfficeWorkspace {
|
||||
param(
|
||||
[string]$Root = (Join-Path ([IO.Path]::GetTempPath()) 'EmberkomOfficeDeployment'),
|
||||
[ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId = ([guid]::NewGuid().ToString('N'))
|
||||
)
|
||||
# Executable content must never be writable by a standard user.
|
||||
$root = Join-Path $env:ProgramData 'EmberkomOfficeDeployment'
|
||||
# Default to the execution account's temp location (SYSTEM under Syncro).
|
||||
$null = New-Item -ItemType Directory -Path $root -Force -ErrorAction Stop
|
||||
for ($item = Get-Item -LiteralPath $root -Force; $null -ne $item; $item = $item.Parent) {
|
||||
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Deployment path traverses a reparse point: $($item.FullName)" }
|
||||
@@ -149,12 +159,198 @@ function New-OfficeWorkspace {
|
||||
}
|
||||
$acl.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')))
|
||||
Set-Acl -LiteralPath $root -AclObject $acl -ErrorAction Stop
|
||||
$path = Join-Path $root ([guid]::NewGuid().ToString('N'))
|
||||
$path = Join-Path $root $DeploymentId
|
||||
$null = New-Item -ItemType Directory -Path $path -ErrorAction Stop
|
||||
$null = New-Item -ItemType File -Path (Join-Path $path 'user-cleanup.lock') -ErrorAction Stop
|
||||
$path
|
||||
}
|
||||
|
||||
function New-OfficeUserWorkspace {
|
||||
param($Media, [string]$Workspace)
|
||||
# Only deferred user cleanup must survive routine temp purges. SYSTEM's temp
|
||||
# directory may also be inaccessible to the limited users who run this helper.
|
||||
$path = New-OfficeWorkspace -Root (Join-Path $env:ProgramData 'EmberkomOfficeDeployment') -DeploymentId (Split-Path -Leaf $Workspace)
|
||||
$helper = Join-Path $path 'Office-UserCleanup.ps1'
|
||||
Copy-Item -LiteralPath $Media.Helper -Destination $helper -ErrorAction Stop
|
||||
$Media.Helper = $helper
|
||||
$path
|
||||
}
|
||||
|
||||
function Assert-OfficeManagedPath {
|
||||
param([string]$Root, [string]$Path)
|
||||
$base = [IO.Path]::GetFullPath($Root).TrimEnd('\')
|
||||
$target = [IO.Path]::GetFullPath($Path)
|
||||
if (!$target.StartsWith($base + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "Path is outside the Office deployment root: $target" }
|
||||
# Check ancestors before enumeration; never follow a junction during deletion or reuse.
|
||||
for ($cursor = $target; $cursor; $cursor = Split-Path -Parent $cursor) {
|
||||
if (Test-Path -LiteralPath $cursor) {
|
||||
if ((Get-Item -LiteralPath $cursor -Force -ErrorAction Stop).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Deployment path traverses a reparse point: $cursor" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Get-OfficeManagedFiles {
|
||||
param([string]$Root, [string]$Path)
|
||||
Assert-OfficeManagedPath $Root $Path
|
||||
if (!(Test-Path -LiteralPath $Path)) { return }
|
||||
$item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
|
||||
if (!$item.PSIsContainer) { return $item }
|
||||
foreach ($child in @(Get-ChildItem -LiteralPath $Path -Force -ErrorAction Stop)) {
|
||||
# Recurse ourselves so a nested junction is rejected BEFORE visiting its target.
|
||||
Get-OfficeManagedFiles $Root $child.FullName
|
||||
}
|
||||
}
|
||||
|
||||
function Remove-OfficeManagedItem {
|
||||
param([string]$Root, [string]$Path)
|
||||
Assert-OfficeManagedPath $Root $Path
|
||||
if (!(Test-Path -LiteralPath $Path)) { return }
|
||||
$null = @(Get-OfficeManagedFiles $Root $Path)
|
||||
$null = Write-Output "Removing deployment artifact: $Path"
|
||||
Remove-Item -LiteralPath ([IO.Path]::GetFullPath($Path)) -Recurse -Force -ErrorAction Stop
|
||||
}
|
||||
|
||||
function Get-OfficeStagingNames {
|
||||
# Only our downloaded artifacts; never Office's installed files or servicing caches.
|
||||
@('ODT', 'odt.exe', 'odt-download-page.html', 'GetHelp', 'GetHelp.zip', 'media-cache.json')
|
||||
foreach ($installer in (Get-OfficeDeploymentDefinitions).CompanionInstallers.Values) { $installer.File }
|
||||
}
|
||||
|
||||
function 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
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-OfficeMicrosoftSignature {
|
||||
param([string]$Path)
|
||||
$signature = Get-AuthenticodeSignature -LiteralPath $Path -ErrorAction Stop
|
||||
@@ -163,12 +359,13 @@ function Assert-OfficeMicrosoftSignature {
|
||||
}
|
||||
|
||||
function Save-OfficeDownload {
|
||||
param([string]$Uri, [string]$Path)
|
||||
param([string]$Uri, [string]$Path, [int]$TimeoutSeconds = 0)
|
||||
$definitions = Get-OfficeDeploymentDefinitions
|
||||
if (!$TimeoutSeconds) { $TimeoutSeconds = $definitions.DownloadTimeoutSeconds }
|
||||
for ($attempt = 1; $attempt -le $definitions.DownloadAttempts; $attempt++) {
|
||||
try {
|
||||
$null = Write-Output "Download attempt ${attempt}: $Uri -> $Path"
|
||||
Invoke-WebRequest -UseBasicParsing -Uri $Uri -OutFile $Path -TimeoutSec $definitions.DownloadTimeoutSeconds -ErrorAction Stop
|
||||
Invoke-WebRequest -UseBasicParsing -Uri $Uri -OutFile $Path -TimeoutSec $TimeoutSeconds -ErrorAction Stop
|
||||
if ((Get-Item -LiteralPath $Path -ErrorAction Stop).Length -eq 0) { throw 'Download was empty.' }
|
||||
return
|
||||
} catch {
|
||||
@@ -189,11 +386,33 @@ function Get-OfficeOdtDownloadUrl {
|
||||
|
||||
function Invoke-OfficeProcess {
|
||||
param([string]$FilePath, [string]$Arguments, [string]$LogPrefix)
|
||||
$null = Write-Output "Running: $FilePath $Arguments. Process logs: $LogPrefix"
|
||||
$process = Start-Process -FilePath $FilePath -ArgumentList $Arguments -WorkingDirectory (Split-Path -Parent $FilePath) -Wait -PassThru -WindowStyle Hidden -RedirectStandardOutput "$LogPrefix.stdout.log" -RedirectStandardError "$LogPrefix.stderr.log" -ErrorAction Stop
|
||||
if ($null -eq $process.ExitCode) { throw "No exit code returned from $FilePath." }
|
||||
$null = Write-Output "Process exited $($process.ExitCode): $FilePath"
|
||||
[int]$process.ExitCode
|
||||
$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
|
||||
}
|
||||
}
|
||||
|
||||
function New-OfficeConfiguration {
|
||||
@@ -231,12 +450,44 @@ function New-OfficeConfiguration {
|
||||
return ,$xml
|
||||
}
|
||||
|
||||
function New-OfficeRemovalConfiguration {
|
||||
param($Options)
|
||||
$xml = New-Object Xml.XmlDocument
|
||||
$configuration = $xml.CreateElement('Configuration'); $null = $xml.AppendChild($configuration)
|
||||
$remove = $xml.CreateElement('Remove'); $remove.SetAttribute('All', 'TRUE'); $null = $configuration.AppendChild($remove)
|
||||
$display = $xml.CreateElement('Display'); $display.SetAttribute('Level', 'None'); $display.SetAttribute('AcceptEULA', 'TRUE'); $null = $configuration.AppendChild($display)
|
||||
$property = $xml.CreateElement('Property'); $property.SetAttribute('Name', 'FORCEAPPSHUTDOWN')
|
||||
$property.SetAttribute('Value', $(if ($Options.OfficeAppShutdown -eq 'Force') { 'TRUE' } else { 'FALSE' })); $null = $configuration.AppendChild($property)
|
||||
# Remove applies to Click-to-Run. RemoveMSI belongs to the installation configuration:
|
||||
# ODT removes MSI Office before installing the replacement product in that operation.
|
||||
return ,$xml
|
||||
}
|
||||
|
||||
function Initialize-OfficeMedia {
|
||||
param($Options, [string]$Workspace)
|
||||
$definitions = Get-OfficeDeploymentDefinitions
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$page = Invoke-WebRequest -UseBasicParsing -Uri $definitions.OdtPage -TimeoutSec $definitions.OdtPageTimeoutSeconds -ErrorAction Stop
|
||||
$url = Get-OfficeOdtDownloadUrl $page.Content
|
||||
# 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)
|
||||
$package = Join-Path $Workspace 'odt.exe'
|
||||
$null = Write-Output "Downloading current ODT from $url"
|
||||
Save-OfficeDownload $url $package
|
||||
@@ -245,27 +496,18 @@ function Initialize-OfficeMedia {
|
||||
$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
|
||||
# Microsoft's evergreen Get Help link retains its historical SaRA name.
|
||||
$scrubZip = Join-Path $Workspace 'GetHelp.zip'
|
||||
Save-OfficeDownload $definitions.GetHelpUrl $scrubZip
|
||||
$scrubFolder = Join-Path $Workspace 'GetHelp'
|
||||
$null = Write-Output "Extracting Get Help: $scrubZip -> $scrubFolder"
|
||||
# Tools.ps1 overrides Expand-Archive with a Path-only wrapper. Use the PS 5.1
|
||||
# module explicitly for literal paths, while keeping diagnostics in the Tools log.
|
||||
Microsoft.PowerShell.Archive\Expand-Archive -LiteralPath $scrubZip -DestinationPath $scrubFolder -ErrorAction Stop
|
||||
$scrub = @(Get-ChildItem -LiteralPath $scrubFolder -Filter $definitions.GetHelpExecutable -File -Recurse)
|
||||
if ($scrub.Count -ne 1) { throw "Microsoft download did not contain exactly one $($definitions.GetHelpExecutable)." }
|
||||
Assert-OfficeMicrosoftSignature $scrub[0].FullName
|
||||
# Run-Script only downloads the core file, so stage its helper explicitly.
|
||||
$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.' }
|
||||
$removalPath = Join-Path $Workspace 'remove.xml'
|
||||
$removal = New-OfficeRemovalConfiguration $Options; $removal.Save($removalPath)
|
||||
$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.'
|
||||
$code = Invoke-OfficeProcess $setup "/download `"$configPath`"" (Join-Path $Workspace 'office-download')
|
||||
for ($attempt = 1; $attempt -le $definitions.DownloadAttempts; $attempt++) {
|
||||
$prefix = if ($attempt -eq 1) { 'office-download' } else { "office-download.retry-$attempt" }
|
||||
$code = Invoke-OfficeProcess $setup "/download `"$configPath`"" (Join-Path $Workspace $prefix)
|
||||
if ($code -eq 0 -or $attempt -eq $definitions.DownloadAttempts) { break }
|
||||
$null = Write-Output "Office download failed ($code); retrying download into the same staging folder (attempt $attempt of $($definitions.DownloadAttempts))."
|
||||
Start-Sleep -Seconds ($definitions.DownloadRetrySeconds * $attempt)
|
||||
}
|
||||
if ($code -ne 0) { throw "Office download failed ($code). Existing Office has not been removed." }
|
||||
$versions = @(Get-ChildItem -LiteralPath (Join-Path $odtFolder 'Office\Data') -Directory -ErrorAction Stop | Where-Object { $_.Name -match $definitions.OfficeBuildPattern })
|
||||
if ($versions.Count -ne 1) { throw 'Office download did not produce one identifiable build.' }
|
||||
@@ -275,7 +517,9 @@ function Initialize-OfficeMedia {
|
||||
}
|
||||
$config.Configuration.Add.SetAttribute('Version', $versions[0].Name); $config.Save($configPath)
|
||||
$companions = Initialize-OfficeCompanionMedia $Workspace -InstallTeams $Options.InstallTeams
|
||||
[pscustomobject]@{ Setup = $setup; Scrubber = $scrub[0].FullName; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions }
|
||||
$media = [pscustomobject]@{ Setup = $setup; RemovalConfig = $removalPath; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions; CachedMediaReused=$false }
|
||||
Save-OfficeMediaCache $Options $media $Workspace
|
||||
$media
|
||||
}
|
||||
|
||||
function Get-OfficeRunningApps {
|
||||
@@ -288,7 +532,13 @@ function Stop-OfficeDeploymentApps {
|
||||
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.'
|
||||
$running | Stop-Process -Force -ErrorAction Stop
|
||||
foreach ($process in $running) {
|
||||
try { Stop-Process -InputObject $process -Force -ErrorAction Stop }
|
||||
catch {
|
||||
if (!$process.HasExited) { throw }
|
||||
$null = Write-Output "Process $($process.Id) exited before it could be stopped; continuing."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Get-OfficeCompanionDownloads {
|
||||
@@ -348,7 +598,7 @@ function Install-OfficeCompanionApps {
|
||||
$code = Invoke-OfficeProcess $Media.WebView2 $definitions.CompanionInstallers.WebView2.Arguments (Join-Path $Workspace 'webview2-install')
|
||||
if ($code -notin @(0, 3010)) { throw "WebView2 installation failed (exit $code)." }
|
||||
if ($code -eq 3010) { $reboot = $true }
|
||||
$webViewVersion = Get-OfficeMachineWebViewVersion
|
||||
$webViewVersion = Wait-OfficeResult { Get-OfficeMachineWebViewVersion } 'machine WebView2 registration'
|
||||
if (!$webViewVersion) { throw 'WebView2 setup returned success but no machine-wide runtime was detected.' }
|
||||
}
|
||||
$versions = [ordered]@{ WebView2=$webViewVersion }
|
||||
@@ -362,11 +612,11 @@ function Install-OfficeCompanionApps {
|
||||
if ($code -notin @(0, 3010)) { throw "$($app.Name) installation failed (exit $code). See logs in $Workspace." }
|
||||
if ($code -eq 3010) { $reboot = $true }
|
||||
if ($app.Package) {
|
||||
$packages = @(Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.DisplayName -eq $app.Package -and $_.PackageName -like ('*' + $definitions.AppxPublisherSuffix) })
|
||||
$packages = @(Wait-OfficeResult { Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.DisplayName -eq $app.Package -and $_.PackageName -like ('*' + $definitions.AppxPublisherSuffix) } } "$($app.Name) provisioning")
|
||||
if (!$packages.Count) { throw "$($app.Name) setup returned success but the app was not provisioned for all users." }
|
||||
$versions[$app.Name] = ($packages.Version | Sort-Object -Unique) -join ', '
|
||||
} else {
|
||||
$oneDrive = Get-OfficeMachineOneDrive
|
||||
$oneDrive = Wait-OfficeResult { Get-OfficeMachineOneDrive } 'per-machine OneDrive registration'
|
||||
if (!$oneDrive) { throw 'OneDrive setup returned success but a per-machine installation was not detected.' }
|
||||
Assert-OfficeMicrosoftSignature $oneDrive.Path
|
||||
$versions.OneDrive = $oneDrive.Version
|
||||
@@ -401,28 +651,58 @@ function Get-OfficeSuiteInventory {
|
||||
$_.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)'
|
||||
}
|
||||
$c2r = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration' -ErrorAction SilentlyContinue
|
||||
if ($c2r.ProductReleaseIds) { [pscustomobject]@{ DisplayName = "Click-to-Run: $($c2r.ProductReleaseIds)" } }
|
||||
}
|
||||
|
||||
function Assert-OfficeScrubResult {
|
||||
param([int]$ExitCode, [string]$Output, [object[]]$RemainingOffice)
|
||||
# Microsoft's scenario output is checked separately from the process exit code.
|
||||
$definitions = Get-OfficeDeploymentDefinitions
|
||||
$results = [regex]::Matches($Output, $definitions.ScrubScenarioPattern)
|
||||
if (!$results.Count) { throw "Get Help returned no recognizable scenario result (process exit $ExitCode). Check scrub logs." }
|
||||
$result = $results[$results.Count - 1].Groups[1].Value
|
||||
if ($result -notin $definitions.ScrubScenarioSuccess -or $ExitCode -notin $definitions.ScrubExitSuccess) { throw "Get Help removal failed: scenario $result, process $ExitCode. Check scrub logs." }
|
||||
if (@($RemainingOffice).Count) { throw "Office remains after cleanup: $(($RemainingOffice | ForEach-Object { $_.DisplayName }) -join '; '). Reboot/repair and rerun; installation stopped." }
|
||||
$key = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration'
|
||||
if (Test-Path -LiteralPath $key -ErrorAction Stop) {
|
||||
$c2r = Get-ItemProperty -LiteralPath $key -ErrorAction Stop
|
||||
if ($c2r.ProductReleaseIds) { [pscustomobject]@{ DisplayName = "Click-to-Run: $($c2r.ProductReleaseIds)" } }
|
||||
}
|
||||
}
|
||||
|
||||
function Remove-OfficeSuite {
|
||||
param($Media, [string]$Workspace)
|
||||
$null = Write-Output 'Removing Office, including Visio and Project, with Microsoft Get Help.'
|
||||
$prefix = Join-Path $Workspace 'office-scrub'
|
||||
$code = Invoke-OfficeProcess $Media.Scrubber (Get-OfficeDeploymentDefinitions).ScrubArguments $prefix
|
||||
$output = (Get-Content -LiteralPath "$prefix.stdout.log" -Raw -ErrorAction Stop) + (Get-Content -LiteralPath "$prefix.stderr.log" -Raw -ErrorAction Stop)
|
||||
Assert-OfficeScrubResult $code $output @(Get-OfficeSuiteInventory)
|
||||
# Get Help can create an interactive elevated child despite a hidden SYSTEM parent.
|
||||
# Never fall back to it automatically. ODT owns the supported silent removal path.
|
||||
$existing = @(Get-OfficeSuiteInventory)
|
||||
$msi = @($existing | Where-Object { $_.WindowsInstaller -eq 1 })
|
||||
if ($msi.Count) { $null = Write-Output "MSI Office will be removed by ODT RemoveMSI before it installs the replacement suite: $($msi.DisplayName -join '; ')." }
|
||||
if (!@($existing | Where-Object { $_.WindowsInstaller -ne 1 }).Count) {
|
||||
$null = Write-Output 'No non-MSI Office products detected; skipping the separate ODT removal pass.'
|
||||
return 0
|
||||
}
|
||||
if (!$Media.RemovalConfig -or !(Test-Path -LiteralPath $Media.RemovalConfig -PathType Leaf)) { throw 'The staged silent Office removal configuration is missing.' }
|
||||
$null = Write-Output 'Silently removing Click-to-Run Office, including Visio and Project, with ODT.'
|
||||
$code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.RemovalConfig)`"" (Join-Path $Workspace 'office-remove')
|
||||
$manual = "No interactive scrubber was launched. Arrange an attended manual scrub if needed: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)"
|
||||
if ($code -notin @(0, 3010)) { throw "Silent ODT Office removal failed (exit $code). See logs in $Workspace. $manual" }
|
||||
if ($code -eq 3010) { return 3010 }
|
||||
$removed = Wait-OfficeResult { @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 }).Count -eq 0 } 'Click-to-Run Office removal registration'
|
||||
if (!$removed) {
|
||||
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 })
|
||||
throw "Office remains after silent ODT removal: $($remaining.DisplayName -join '; '). Installation stopped. $manual"
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
function Test-OfficeCanDeferRestart {
|
||||
param($Options, [ValidateSet('Office', 'Companions')][string]$Stage)
|
||||
if ($Options.DeferReboot -isnot [bool]) { throw 'DeferReboot must be a validated Boolean before deciding whether to continue.' }
|
||||
if (!$Options.DeferReboot) {
|
||||
$null = Write-Output "$Stage removal requested a restart. DeferReboot=false; stopping before replacement installation."
|
||||
return $false
|
||||
}
|
||||
# A 3010 result is success with a restart pending, not permission to ignore
|
||||
# incomplete removal. Verify the old products are gone before deferring it.
|
||||
$verified = Wait-OfficeResult {
|
||||
if ($Stage -eq 'Office') { return @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 }).Count -eq 0 }
|
||||
@(Get-OfficeMachineCompanionEntries).Count -eq 0
|
||||
} "$Stage removal before deferring its restart"
|
||||
if ($verified) {
|
||||
$null = Write-Output "$Stage removal verified. Deferring the requested restart until after deployment; the final result will retain exit code 3010."
|
||||
return $true
|
||||
}
|
||||
$remaining = @(if ($Stage -eq 'Office') { Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 } } else { Get-OfficeMachineCompanionEntries })
|
||||
$null = Write-Output "Cannot defer the $Stage removal restart: registrations remain for $($remaining.DisplayName -join '; '). Restart and rerun before replacement installation."
|
||||
return $false
|
||||
}
|
||||
|
||||
function Get-OfficeAppxNames {
|
||||
@@ -443,25 +723,93 @@ function Get-OfficeOneDriveCommand {
|
||||
[pscustomobject]@{ FilePath = $exe; Arguments = $arguments }
|
||||
}
|
||||
|
||||
function Test-OfficeMachineMsiProduct {
|
||||
param([Parameter(Mandatory=$true)][ValidatePattern('^\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\}$')][string]$ProductCode)
|
||||
if (!('Emberkom.OfficeMachineMsi' -as [type])) {
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
namespace Emberkom {
|
||||
public static class OfficeMachineMsi {
|
||||
[DllImport("msi.dll", CharSet=CharSet.Unicode, ExactSpelling=true)]
|
||||
private static extern uint MsiEnumProductsExW(string product, string userSid, uint context, uint index, IntPtr code, IntPtr installedContext, IntPtr sid, IntPtr sidLength);
|
||||
public static uint Find(string product) {
|
||||
// MSIINSTALLCONTEXT_MACHINE requires a native NULL user SID.
|
||||
return MsiEnumProductsExW(product, null, 4, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
# Read-only MSI enumeration avoids Win32_Product and its repair side effects.
|
||||
$code = [Emberkom.OfficeMachineMsi]::Find($ProductCode)
|
||||
if ($code -eq 0) { return $true }
|
||||
if ($code -in @(259, 1605)) { return $false }
|
||||
throw "Cannot determine machine MSI registration for $ProductCode (Win32 $code)."
|
||||
}
|
||||
|
||||
function Get-OfficeMachineCompanionEntries {
|
||||
$definitions = Get-OfficeDeploymentDefinitions
|
||||
foreach ($entry in @(Get-OfficeUninstallEntries)) {
|
||||
if ($entry.DisplayName -notin (@('Microsoft OneDrive') + $definitions.TeamsMsiNames)) { continue }
|
||||
if ($entry.DisplayName -eq 'Microsoft Teams Meeting Add-in for Microsoft Office' -and !(Test-OfficeMachineMsiProduct $entry.PSChildName)) {
|
||||
# Some per-user add-ins advertise themselves in HKLM. Their registration alone
|
||||
# does not mean SYSTEM can uninstall them. The user helper checks both hives.
|
||||
$null = Write-Output "No machine MSI registration for $($entry.DisplayName) $($entry.DisplayVersion), $($entry.PSChildName). Per-user registration will be checked by user cleanup. Registry entry: $($entry.PSPath)"
|
||||
continue
|
||||
}
|
||||
$entry
|
||||
}
|
||||
}
|
||||
|
||||
function Remove-OfficeAppxEntry {
|
||||
param([string]$PackageName, [switch]$Provisioned)
|
||||
$definitions = Get-OfficeDeploymentDefinitions
|
||||
for ($attempt = 1; $attempt -le $definitions.AppxRemovalAttempts; $attempt++) {
|
||||
$null = Write-Output "Removing Appx package $PackageName (provisioned=$Provisioned, attempt $attempt)."
|
||||
try {
|
||||
if ($Provisioned) { $null = Remove-AppxProvisionedPackage -Online -PackageName $PackageName -AllUsers -ErrorAction Stop }
|
||||
else { Remove-AppxPackage -Package $PackageName -AllUsers -ErrorAction Stop }
|
||||
} catch {
|
||||
# Another removal can already have removed this registration. Verify before failing.
|
||||
$null = Write-Output "Appx removal reported an error for ${PackageName}: $($_.Exception.Message). Checking state before retrying."
|
||||
}
|
||||
$gone = Wait-OfficeResult {
|
||||
$registered = @(if ($Provisioned) {
|
||||
Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.PackageName -eq $PackageName }
|
||||
} else {
|
||||
Get-AppxPackage -AllUsers -ErrorAction Stop | Where-Object { $_.PackageFullName -eq $PackageName }
|
||||
})
|
||||
$registered.Count -eq 0
|
||||
} "removal of $PackageName"
|
||||
if ($gone) { return }
|
||||
}
|
||||
throw "Appx package remains after $($definitions.AppxRemovalAttempts) removal attempts: $PackageName. Check the diagnostic log."
|
||||
}
|
||||
|
||||
function Remove-OfficeCompanionApps {
|
||||
param([string]$Workspace)
|
||||
$names = Get-OfficeAppxNames
|
||||
$definitions = Get-OfficeDeploymentDefinitions
|
||||
foreach ($package in @(Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.DisplayName -in $names })) {
|
||||
$null = Write-Output "Removing provisioned package: $($package.PackageName)"
|
||||
$null = Remove-AppxProvisionedPackage -Online -PackageName $package.PackageName -AllUsers -ErrorAction Stop
|
||||
Remove-OfficeAppxEntry $package.PackageName -Provisioned
|
||||
}
|
||||
foreach ($package in @(Get-AppxPackage -AllUsers -ErrorAction Stop | Where-Object { $_.Name -in $names })) {
|
||||
$null = Write-Output "Removing installed package: $($package.PackageFullName)"
|
||||
Remove-AppxPackage -Package $package.PackageFullName -AllUsers -ErrorAction Stop
|
||||
Remove-OfficeAppxEntry $package.PackageFullName
|
||||
}
|
||||
if (@(Get-AppxPackage -AllUsers -ErrorAction Stop | Where-Object { $_.Name -in $names }).Count) { throw 'Office/Teams/Outlook Store packages remain after removal.' }
|
||||
$gone = Wait-OfficeResult {
|
||||
$installed = @(Get-AppxPackage -AllUsers -ErrorAction Stop | Where-Object { $_.Name -in $names })
|
||||
$provisioned = @(Get-AppxProvisionedPackage -Online -ErrorAction Stop | Where-Object { $_.DisplayName -in $names })
|
||||
($installed.Count + $provisioned.Count) -eq 0
|
||||
} 'Office/Teams/Outlook Store package removal'
|
||||
if (!$gone) { throw 'Office/Teams/Outlook Store packages remain after removal.' }
|
||||
$reboot = $false
|
||||
foreach ($entry in @(Get-OfficeUninstallEntries)) {
|
||||
foreach ($entry in @(Get-OfficeMachineCompanionEntries)) {
|
||||
$null = Write-Output "Removing machine companion: $($entry.DisplayName) $($entry.DisplayVersion). Registry entry: $($entry.PSPath)"
|
||||
if ($entry.DisplayName -in $definitions.TeamsMsiNames) {
|
||||
if ($entry.PSChildName -notmatch '^\{[0-9A-Fa-f-]{36}\}$') { throw 'Teams MSI has an unexpected product code.' }
|
||||
$prefix = Join-Path $Workspace ('teams-' + $entry.PSChildName)
|
||||
$code = Invoke-OfficeProcess "$env:WINDIR\System32\msiexec.exe" "/x $($entry.PSChildName) /qn /norestart /L*v `"$prefix.log`"" $prefix
|
||||
$code = Invoke-OfficeProcess "$env:WINDIR\System32\msiexec.exe" "/x $($entry.PSChildName) /qn /norestart /L+*v `"$prefix.log`"" $prefix
|
||||
} elseif ($entry.DisplayName -eq 'Microsoft OneDrive') {
|
||||
$roots = @((Join-Path $env:ProgramFiles 'Microsoft OneDrive'), (Join-Path $env:WINDIR 'System32'), (Join-Path $env:WINDIR 'SysWOW64'))
|
||||
if (${env:ProgramFiles(x86)}) { $roots += Join-Path ${env:ProgramFiles(x86)} 'Microsoft OneDrive' }
|
||||
@@ -472,7 +820,13 @@ function Remove-OfficeCompanionApps {
|
||||
if ($code -eq 3010) { $reboot = $true }
|
||||
elseif ($code -notin @(0, 1605, 1614)) { throw "Could not remove $($entry.DisplayName) (exit $code)." }
|
||||
}
|
||||
if (@(Get-OfficeUninstallEntries | Where-Object { $_.DisplayName -in (@('Microsoft OneDrive') + $definitions.TeamsMsiNames) }).Count -and !$reboot) { throw 'A machine-wide Teams/OneDrive installation remains after removal.' }
|
||||
if (!$reboot) { $null = Wait-OfficeResult { @(Get-OfficeMachineCompanionEntries).Count -eq 0 } 'machine companion removal registration' }
|
||||
$remaining = @(Get-OfficeMachineCompanionEntries)
|
||||
if ($remaining.Count) {
|
||||
$details = ($remaining | ForEach-Object { "$($_.DisplayName) $($_.DisplayVersion) [$($_.PSPath)]" }) -join '; '
|
||||
$null = Write-Output "Machine companion registrations remaining after removal: $details"
|
||||
if (!$reboot) { throw "Machine companion registrations remain after removal: $details. Check uninstall logs in $Workspace. Office removal/installation has not started." }
|
||||
}
|
||||
$reboot
|
||||
}
|
||||
|
||||
@@ -547,7 +901,10 @@ function Start-OfficeUserCleanup {
|
||||
$pending = @()
|
||||
foreach ($task in $tasks) {
|
||||
$marker = Get-ItemPropertyValue -LiteralPath "Registry::HKEY_USERS\$($task.SID)\Software\Emberkom\OfficeDeployment\$deploymentId" -Name Status -ErrorAction SilentlyContinue
|
||||
if ($marker -eq 'Complete') { Unregister-ScheduledTask -TaskName $task.Name -Confirm:$false -ErrorAction Stop }
|
||||
if ($marker -eq 'Complete') {
|
||||
try { Unregister-ScheduledTask -TaskName $task.Name -Confirm:$false -ErrorAction Stop }
|
||||
catch { $null = Write-Output "Cleanup completed, but its task could not be unregistered: $($task.Name). The Complete marker makes it a no-op. $($_.Exception.Message)" }
|
||||
}
|
||||
else { $pending += $task.SID; $null = Write-Output "Cleanup pending for $($task.SID); task $($task.Name) runs at their next sign-in." }
|
||||
}
|
||||
return ,$pending
|
||||
@@ -555,11 +912,24 @@ function Start-OfficeUserCleanup {
|
||||
|
||||
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." }
|
||||
$installed = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration' -ErrorAction Stop
|
||||
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)"
|
||||
}
|
||||
$platform = if ($Options.OfficeArchitecture -eq '64') { 'x64' } else { 'x86' }
|
||||
if ($Options.ProductId -notin ($installed.ProductReleaseIds -split ',') -or $installed.Platform -ne $platform -or $installed.VersionToReport -ne $Media.Version) { throw 'Setup exited successfully but the installed product, architecture, or version did not match.' }
|
||||
$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 }
|
||||
$code
|
||||
}
|
||||
|
||||
@@ -569,6 +939,7 @@ function Invoke-OfficeDeployment {
|
||||
# Internal action messages use Tools.ps1's logger. Suppress its echoed success output
|
||||
# so it cannot become part of a function's return value. Entry prints the Syncro receipt.
|
||||
if ($Options.ValidateBeforeChanges -isnot [bool]) { throw 'ValidateBeforeChanges must be a validated Boolean before running the workload.' }
|
||||
if ($Options.DeferReboot -isnot [bool]) { throw 'DeferReboot must be a validated Boolean before running the workload.' }
|
||||
Assert-OfficeDeploymentHost $Options
|
||||
$mutex = New-Object Threading.Mutex($false, 'Global\EmberkomOfficeDeployment')
|
||||
$locked = $false
|
||||
@@ -578,8 +949,9 @@ function Invoke-OfficeDeployment {
|
||||
$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). Workspace: $workspace"
|
||||
$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
|
||||
$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) {
|
||||
@@ -588,34 +960,49 @@ function Invoke-OfficeDeployment {
|
||||
$media = Initialize-OfficeMedia $Options $workspace
|
||||
if ($Options.ValidateBeforeChanges) {
|
||||
$existingOffice = @(Get-OfficeSuiteInventory | ForEach-Object { $_.DisplayName })
|
||||
$null = Write-Output 'Validation passed. Stopped before closing apps, uninstalling, clearing identities, registering tasks, or installing.'
|
||||
# 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.'
|
||||
return [pscustomobject]@{
|
||||
OfficeDeploymentStatus='ValidationPassed'; ExitCode=0; ValidateBeforeChanges=$true
|
||||
ProductId=$Options.ProductId; OfficeVersion=$media.Version; Architecture=$Options.OfficeArchitecture
|
||||
UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams
|
||||
UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams; OfficeRemovalMethod='SilentODT'; DeferReboot=$Options.DeferReboot
|
||||
Workspace=$workspace; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps
|
||||
NextStep='Set ValidateBeforeChanges=false to deploy. That run repeats validation and downloads fresh media.'
|
||||
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.'
|
||||
}
|
||||
}
|
||||
Stop-OfficeDeploymentApps $Options
|
||||
$reboot = Remove-OfficeCompanionApps $workspace
|
||||
if ($reboot) {
|
||||
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; Workspace = $workspace; PendingUserSids = @() }
|
||||
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 = @() }
|
||||
}
|
||||
Remove-OfficeSuite $media $workspace
|
||||
foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile }
|
||||
$pending = Start-OfficeUserCleanup $profiles $media $workspace
|
||||
Set-OfficeReinstallPhase $workspace
|
||||
$userWorkspace = $workspace
|
||||
if ($profiles.Count) { $userWorkspace = New-OfficeUserWorkspace $media $workspace }
|
||||
$pending = Start-OfficeUserCleanup $profiles $media $userWorkspace
|
||||
Set-OfficeReinstallPhase $userWorkspace
|
||||
$code = Install-OfficeMedia $Options $media $workspace
|
||||
$companions = Install-OfficeCompanionApps $media.Companions $workspace -InstallTeams $Options.InstallTeams
|
||||
if ($companions.ExitCode -eq 3010) { $code = 3010 }
|
||||
if ($reboot -or $removalCode -eq 3010 -or $companions.ExitCode -eq 3010) { $code = 3010 }
|
||||
$status = if ($pending.Count) { 'InstalledWithUserCleanupPending' } else { 'Installed' }
|
||||
$null = Write-Output "$status. Office $($media.Version), $($Options.ProductId). Restart after the Office scrub is recommended; no automatic reboot was requested."
|
||||
$null = Write-Output "$status. Office $($media.Version), $($Options.ProductId). No automatic reboot was requested."
|
||||
$provisionedApps = if ($Options.InstallTeams) { 'Teams and new Outlook are' } else { 'New Outlook is' }
|
||||
$null = Write-Output "$provisionedApps provisioned for all users; OneDrive is installed per-machine. Users may need to sign out and back in to register the apps."
|
||||
$null = Write-Output 'Windows work-account/WAM sign-in is preserved; Windows SSO can sign Office in again. App installation does not grant Teams or mailbox entitlements.'
|
||||
[pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if ($pending.Count -and $code -eq 0) { 2 } else { $code }); ValidateBeforeChanges=$false; Workspace = $workspace; PendingUserSids = $pending; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version }
|
||||
$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 -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; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version; CachedMediaReused=[bool]$media.CachedMediaReused; ArtifactCleanupPending=($cleanupWarnings.Count -gt 0) }
|
||||
} finally {
|
||||
if ($locked) { $mutex.ReleaseMutex() }
|
||||
$mutex.Dispose()
|
||||
@@ -669,9 +1056,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 staging current installers/Office media (several GB). No app shutdown, cleanup, or installation will run.'
|
||||
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.'
|
||||
} else {
|
||||
Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: validating and staging media, then removing and reinstalling Office and the selected companion apps.'
|
||||
Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: validating and staging media, then silently removing Office with ODT and reinstalling Office and the selected companion apps.'
|
||||
}
|
||||
Microsoft.PowerShell.Utility\Write-Output "Diagnostic log: $Global:LogFile"
|
||||
$results = @(Invoke-OfficeDeployment -Options $options)
|
||||
@@ -682,13 +1069,15 @@ function Invoke-OfficeDeploymentEntry {
|
||||
$null = Write-Output $receipt
|
||||
Microsoft.PowerShell.Utility\Write-Output $receipt
|
||||
if ($deployment[0].OfficeDeploymentStatus -like 'Installed*') {
|
||||
Microsoft.PowerShell.Utility\Write-Output 'Restart after the Office scrub is recommended. Users may need to sign out and back in for companion app registration; check PendingUserSids for deferred cleanup.'
|
||||
if ($deployment[0].ArtifactCleanupPending) { Microsoft.PowerShell.Utility\Write-Output 'WARNING: Installation succeeded, but some deployment files could not be cleaned up. See the diagnostic log; no background cleanup is scheduled.' }
|
||||
if ($deployment[0].ExitCode -eq 3010) { Microsoft.PowerShell.Utility\Write-Output 'A restart is required to finish deployment; no automatic reboot was requested.' }
|
||||
Microsoft.PowerShell.Utility\Write-Output 'Users may need to sign out and back in for companion app registration; check PendingUserSids for deferred cleanup.'
|
||||
}
|
||||
$ExitCode.Value = [int]$deployment[0].ExitCode
|
||||
}
|
||||
|
||||
$OfficeInputValues = @{}
|
||||
foreach ($OfficeInputName in @('OfficeSubscription', 'OfficeArchitecture', 'UpdateChannel', 'OfficeActivation', 'OfficeAppShutdown', 'ValidateBeforeChanges', 'COMPANY')) {
|
||||
foreach ($OfficeInputName in @('OfficeSubscription', 'OfficeArchitecture', 'UpdateChannel', 'OfficeActivation', 'OfficeAppShutdown', 'DeferReboot', 'ValidateBeforeChanges', 'COMPANY')) {
|
||||
$OfficeInputVariable = Get-Variable -Name $OfficeInputName -ErrorAction SilentlyContinue
|
||||
$OfficeInputValues[$OfficeInputName] = if ($null -ne $OfficeInputVariable) { [string]$OfficeInputVariable.Value } else { '' }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user