Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2163a6158 | ||
|
|
f9daec0542 |
+79
-160
@@ -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.
|
||||
# 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
|
||||
$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
|
||||
Remove-OfficeStagingFiles $root $Workspace
|
||||
Remove-OfficeManagedItem $root (Join-Path $Workspace 'Office-UserCleanup.ps1')
|
||||
} 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
|
||||
}
|
||||
}
|
||||
$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." }
|
||||
# Small metadata only, including in validation. No persistent staging directory.
|
||||
$historyPath = Join-Path ([IO.Path]::GetTempPath()) ('OfficeReleaseHistory-' + [guid]::NewGuid().ToString('N') + '.html')
|
||||
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
|
||||
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.'
|
||||
}
|
||||
|
||||
+105
-2
@@ -20,6 +20,7 @@ function Get-SystemCleanupDefaults {
|
||||
CleanupDiagnosticDays = 30
|
||||
CleanupBackupDays = 30
|
||||
CleanupSystemTemp = $true
|
||||
CleanupOfficeStaging = $true
|
||||
CleanupUserTemp = $true
|
||||
CleanupServiceTemp = $true
|
||||
CleanupCBSArchives = $true
|
||||
@@ -183,7 +184,9 @@ function Get-SystemCleanupChildren {
|
||||
Write-SystemCleanupMessage "Skipping linked or unsafe path: $Root"
|
||||
return
|
||||
}
|
||||
Get-ChildItem -LiteralPath $Root -Force -ErrorAction Stop | Where-Object { -not ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) }
|
||||
# Office staging has its own mutex/identity/retention rules. Generic temp scans
|
||||
# must not bypass them or remove deferred user-cleanup helpers.
|
||||
Get-ChildItem -LiteralPath $Root -Force -ErrorAction Stop | Where-Object { -not ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -and $_.Name -ne 'EmberkomOfficeDeployment' }
|
||||
}
|
||||
|
||||
function Get-SystemCleanupFiles {
|
||||
@@ -201,6 +204,7 @@ function Get-SystemCleanupFiles {
|
||||
|
||||
function Remove-SystemCleanupFile {
|
||||
param($Context, [string]$Category, [string]$Root, [string]$Path, [datetime]$Cutoff)
|
||||
if ($Category -ne 'OfficeStaging' -and $Path -match '(?i)(^|[\\/])EmberkomOfficeDeployment([\\/]|$)') { return }
|
||||
if (-not (Test-SystemCleanupPath $Path $Root)) { return }
|
||||
$file = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
|
||||
if ($file.PSIsContainer -or $file.LastWriteTimeUtc -ge $Cutoff) { return }
|
||||
@@ -533,6 +537,100 @@ function Remove-SystemCleanupBundle {
|
||||
}
|
||||
}
|
||||
|
||||
function Get-SystemCleanupOfficeStagingRoots {
|
||||
param([string[]]$Profiles)
|
||||
@(
|
||||
(Join-Path ([IO.Path]::GetTempPath()) 'EmberkomOfficeDeployment')
|
||||
(Join-Path $env:SystemRoot 'Temp\EmberkomOfficeDeployment')
|
||||
(Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment')
|
||||
(Join-Path $env:ProgramData 'EmberkomOfficeDeployment')
|
||||
foreach ($profile in $Profiles) { Join-Path $profile 'AppData\Local\Temp\EmberkomOfficeDeployment' }
|
||||
) | Sort-Object -Unique
|
||||
}
|
||||
|
||||
function New-SystemCleanupOfficeMutex {
|
||||
return New-Object Threading.Mutex($false, 'Global\EmberkomOfficeDeployment')
|
||||
}
|
||||
|
||||
function Clear-SystemCleanupOfficeStaging {
|
||||
param($Context, [string[]]$Roots, [datetime]$Cutoff)
|
||||
$rootsPresent = @($Roots | Select-Object -Unique | Where-Object { Test-Path -LiteralPath $_ })
|
||||
if (-not $rootsPresent.Count) { return }
|
||||
$mutex = New-SystemCleanupOfficeMutex
|
||||
$acquired = $false; $retained = 0
|
||||
try {
|
||||
try { $acquired = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $acquired = $true }
|
||||
if (-not $acquired) { Set-SystemCleanupSkipped $Context 'OfficeStaging' 'Office deployment is running; staging retained.'; return }
|
||||
$processes = @(Get-CimInstance Win32_Process -ErrorAction Stop)
|
||||
if (@($processes | Where-Object { $_.Name -in @('setup.exe', 'odt.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe') }).Count) {
|
||||
Set-SystemCleanupSkipped $Context 'OfficeStaging' 'An installer is running; staging retained.'; return
|
||||
}
|
||||
# Match Install-MicrosoftOffice365's disposable artifact allowlist. Never delete
|
||||
# options, logs, XML, user helpers, task markers, locks or the workspace itself.
|
||||
$names = @('ODT', 'odt.exe', 'odt-download-page.html', 'GetHelp', 'GetHelp.zip', 'media-cache.json',
|
||||
'MicrosoftEdgeWebview2Setup.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe')
|
||||
foreach ($root in $rootsPresent) {
|
||||
if (-not (Test-SystemCleanupPath $root $root)) { $retained++; continue }
|
||||
foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -Force -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' })) {
|
||||
try {
|
||||
if (-not (Test-SystemCleanupPath $folder.FullName $root)) { throw 'Linked or unsafe workspace.' }
|
||||
$markerPath = Join-Path $folder.FullName 'options.json'
|
||||
if (-not (Test-Path -LiteralPath $markerPath -PathType Leaf)) { throw 'Missing deployment identity.' }
|
||||
if (-not (Test-SystemCleanupPath $markerPath $root)) { throw 'Linked deployment identity.' }
|
||||
$marker = Get-Item -LiteralPath $markerPath -Force -ErrorAction Stop
|
||||
if ($marker.Length -gt 64KB) { throw 'Oversized deployment identity.' }
|
||||
$options = Get-Content -LiteralPath $markerPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
|
||||
if ($options.ProductId -notin @('O365BusinessRetail','O365BusinessEEANoTeamsRetail','O365ProPlusRetail','O365ProPlusEEANoTeamsRetail') -or
|
||||
$options.OfficeArchitecture -notin @('32','64') -or $options.UpdateChannel -notin @('Current','MonthlyEnterprise','SemiAnnual')) { throw 'Unrecognized deployment identity.' }
|
||||
if ($folder.LastWriteTimeUtc -ge $Cutoff -or $marker.LastWriteTimeUtc -ge $Cutoff) { throw 'Recent deployment.' }
|
||||
foreach ($process in $processes) {
|
||||
foreach ($value in @($process.CommandLine, $process.ExecutablePath)) {
|
||||
if ($value -and $value.IndexOf($folder.FullName, [StringComparison]::OrdinalIgnoreCase) -ge 0) { throw 'Workspace is referenced by a running process.' }
|
||||
}
|
||||
}
|
||||
$items = New-Object 'System.Collections.Generic.List[object]'
|
||||
$pending = New-Object 'System.Collections.Generic.Stack[string]'
|
||||
foreach ($name in $names) {
|
||||
$target = Join-Path $folder.FullName $name
|
||||
if (Test-Path -LiteralPath $target) { $pending.Push($target) }
|
||||
}
|
||||
while ($pending.Count) {
|
||||
$target = $pending.Pop()
|
||||
if (-not (Test-SystemCleanupPath $target $folder.FullName)) { throw 'Linked staging artifact.' }
|
||||
$item = Get-Item -LiteralPath $target -Force -ErrorAction Stop
|
||||
if ($item.LastWriteTimeUtc -ge $Cutoff) { throw 'Recent staging artifact.' }
|
||||
$items.Add($item)
|
||||
if ($item.PSIsContainer) {
|
||||
foreach ($child in @(Get-ChildItem -LiteralPath $target -Force -ErrorAction Stop)) { $pending.Push($child.FullName) }
|
||||
} else {
|
||||
# Probe in preview too; in-use data is not an eligible estimate.
|
||||
$probe = [IO.File]::Open($item.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
|
||||
$probe.Dispose()
|
||||
}
|
||||
}
|
||||
foreach ($file in @($items | Where-Object { -not $_.PSIsContainer })) {
|
||||
Remove-SystemCleanupFile $Context 'OfficeStaging' $folder.FullName $file.FullName $Cutoff
|
||||
}
|
||||
if (-not $Context.Options.ReportOnly) {
|
||||
foreach ($directory in @($items | Where-Object PSIsContainer | Sort-Object { $_.FullName.Length } -Descending)) {
|
||||
if ((Test-SystemCleanupPath $directory.FullName $folder.FullName) -and @(Get-ChildItem -LiteralPath $directory.FullName -Force -ErrorAction Stop).Count -eq 0) {
|
||||
[IO.Directory]::Delete($directory.FullName, $false)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
$retained++
|
||||
Write-SystemCleanupMessage "Office staging retained at $($folder.FullName): $($_.Exception.Message)" -Detail
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($retained) { $Context.Stats.OfficeStaging.Notes = "$retained folder(s) retained: recent, active, unrecognized or unsafe; see verbose." }
|
||||
} finally {
|
||||
if ($acquired) { $mutex.ReleaseMutex() }
|
||||
$mutex.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
function Get-SystemCleanupRecycleDate {
|
||||
param([string]$MetadataPath)
|
||||
if ((Get-Item -LiteralPath $MetadataPath -Force -ErrorAction Stop).Length -gt 1MB) { throw 'Oversized Recycle Bin metadata.' }
|
||||
@@ -700,9 +798,14 @@ function Invoke-SystemCleanup {
|
||||
# Generic temp cleaning must not bypass the AutoCAD process check or dump retention.
|
||||
$tempExclusions = @('*.ac$', '*.sv$', '*.dmp')
|
||||
Invoke-SystemCleanupCategory $context 'SystemTemp' {
|
||||
Clear-SystemCleanupTree $context 'SystemTemp' (Join-Path $env:SystemRoot 'Temp') $tempCutoff -Exclude $tempExclusions -Recurse
|
||||
foreach ($relative in @('Temp', 'SystemTemp')) {
|
||||
Clear-SystemCleanupTree $context 'SystemTemp' (Join-Path $env:SystemRoot $relative) $tempCutoff -Exclude $tempExclusions -Recurse
|
||||
}
|
||||
# Includes .evtx, computer-name logs, AppxErrorReport files, and Chocolatey temp.
|
||||
}
|
||||
Invoke-SystemCleanupCategory $context 'OfficeStaging' {
|
||||
Clear-SystemCleanupOfficeStaging $context (Get-SystemCleanupOfficeStagingRoots $allProfiles) $tempCutoff
|
||||
}
|
||||
Invoke-SystemCleanupCategory $context 'UserTemp' {
|
||||
$acadRunning = Test-SystemCleanupAppRunning @('acad')
|
||||
foreach ($profile in $profiles) {
|
||||
|
||||
@@ -60,19 +60,21 @@ Business Basic, E1, frontline/web-only plans, education/government variants, con
|
||||
|
||||
## Download, removal, and installation
|
||||
|
||||
With `ValidateBeforeChanges=true`, the script checks the subscription/activation combination, host and OS prerequisites, running apps, and availability of registered user profiles. It downloads and verifies ODT, the user cleanup helper, the full Office payload, and the selected companion bootstrappers. It writes the installation/removal XML and options, and returns `ValidationPassed` with `OfficeRemovalMethod=SilentODT`, the selected product, version, company, Teams choice, existing Office inventory, and running apps. It does **not** close apps, uninstall, clear identity/credentials, load user hives, register per-user cleanup tasks, or install apps. `OfficeAppShutdown=Force` only reports running apps in this mode; `Abort` fails validation if any are running.
|
||||
With `ValidateBeforeChanges=true`, the script checks the subscription/activation combination, host and OS prerequisites, running apps, registered profile availability, target release availability when required, and free space. It returns `ValidationPassed` with the deployment plan, existing Office inventory and running apps. It does not create an Office staging workspace, download/extract ODT or any installation media, close apps, uninstall, clear identity/credentials, register tasks, or install apps. `OfficeAppShutdown=Force` only reports running apps; `Abort` fails if any are running.
|
||||
|
||||
Validation writes logs and staging files in the execution account's temp directory, secures its workspace, and runs ODT extraction and `/download` when no reusable cache exists; it is not a zero-write inventory scan. Allow several GB for the first run. It registers no scheduled tasks. A later `false` run repeats prerequisites and reuses matching, unexpired media after checking its file inventory, sizes, and Microsoft executable signatures. The script does not calculate or compare file checksums. The small user cleanup helper is always refreshed from the repository and is deleted from the validation workspace before returning. Validation does not prove tenant entitlements, successful future uninstallation/activation, or availability of the online companion payloads at install time.
|
||||
Windows 10 preflight retrieves small release-history metadata into a temporary file and removes it on success or failure. Other hosts leave the target version unspecified until ODT selects it during installation. Validation still writes the normal Tools log. `Workspace` is null and `MediaDownloaded=false`; `OfficeVersion` is the resolved target on Windows 10 and empty otherwise. Validation does not prove installer download availability, tenant entitlements, future removal/activation, or availability of online companion payloads.
|
||||
|
||||
Disk-space checks reserve **10 GB for installation and companion apps**, plus **6 GB for a fresh media download** on the staging drive. When staging, Windows, and Program Files share C:, this means 16 GB free before a fresh download and 10 GB remaining after staging. A cache hit only needs the installation reserve. Windows and Program Files volumes are checked separately when they differ. Both validation and deployment check again after staging, before app shutdown/removal, so a completed download cannot pass validation with too little space left to install. These are adjustable deployment headroom values in `Get-OfficeDeploymentDefinitions`, not Microsoft's minimum system requirements or a guarantee against concurrent disk use. A space failure reports the drive, available space, and requirement; it preserves staged media for reuse after space is freed. It does not delete unrelated files or add housekeeping tasks.
|
||||
With `ValidateBeforeChanges=false`, the same prerequisites run again before a fresh workspace is created. The script downloads and verifies the full Office payload and selected bootstrappers, rechecks free space and running apps, performs removal/installation, verifies results, and cleans up media in `finally`. Download failures therefore occur before installed apps are removed.
|
||||
|
||||
Disk-space checks reserve **10 GB for installation and companion apps**, plus **6 GB for a fresh media download** on the staging drive. When staging, Windows, and Program Files share C:, validation and initial deployment checks require 16 GB free; installation also requires 10 GB remaining after staging. Separate installation volumes are checked independently. These are adjustable headroom values in `Get-OfficeDeploymentDefinitions`, not Microsoft's minimum requirements or a guarantee against concurrent disk use. Low space fails before app removal. Use `Start-SystemCleanup.ps1` to report/remove abandoned media before retrying; validation never performs housekeeping.
|
||||
|
||||
The script resolves the current versioned ODT download from the [Microsoft Download Center](https://www.microsoft.com/en-us/download/details.aspx?id=49117). It does not depend on the Emberkom-hosted setup.exe or a frozen Microsoft binary URL. If the page format changes, it stops before removal. The downloaded ODT package and extracted setup.exe must have valid Microsoft signatures.
|
||||
|
||||
**Unattended deployment does not download or launch Get Help.** The Get Help build observed on October 14, 2026 created an elevated PowerShell cleanup window in the logged-in user's session even when its parent ran hidden under SYSTEM. Hiding the parent did not hide that child, and Microsoft's documented `-HideProgress` option applies to other scenarios, not Office removal. See the [Get Help command-line reference](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-command-line-overview). The script uses ODT's supported silent removal instead; an interactive scrub is an attended troubleshooting step only.
|
||||
|
||||
On Windows 11, the download and installation XML omit `Version`, letting ODT select the latest available build in the selected channel. Matching staged media can be reused for seven days; ODT may fetch newer files at installation time if the channel has advanced. Verification accepts the staged build or a newer build and reports the actual installed version. There is no fixed build number to maintain.
|
||||
On Windows 11, the download and installation XML omit `Version`, letting ODT select the latest available build in the selected channel. ODT may fetch newer files at installation time if the channel advances during the run. Verification accepts the staged build or a newer build and reports the actual installed version. There is no fixed build number to maintain.
|
||||
|
||||
Windows 10 is the exception: Microsoft limits it to [Office feature release 2608 with subsequent security updates](https://learn.microsoft.com/en-us/microsoft-365-apps/end-of-support/windows-10-support). Before using any cache or removing apps, the script resolves the highest published 2608 build for the selected channel from [Microsoft's release history](https://learn.microsoft.com/en-us/officeupdates/update-history-microsoft365-apps-by-date). Only Windows 10 specifies that build in the download/install XML. A new published build makes older cached media ineligible. Missing release data or a mismatched download stops staging before removal. The feature release and history/channel definitions are centralized at the top of the script; patch build numbers are not hardcoded. Server editions are not classified as Windows 10 by their build number.
|
||||
Windows 10 is the exception: Microsoft limits it to [Office feature release 2608 with subsequent security updates](https://learn.microsoft.com/en-us/microsoft-365-apps/end-of-support/windows-10-support). During prerequisite checks, before downloading installers or removing apps, the script resolves the highest published 2608 build for the selected channel from [Microsoft's release history](https://learn.microsoft.com/en-us/officeupdates/update-history-microsoft365-apps-by-date). Only Windows 10 specifies that build in the download/install XML. Missing release data or a mismatched download stops before removal. The feature release and history/channel definitions are centralized at the top of the script; patch build numbers are not hardcoded. Server editions are not classified as Windows 10 by their build number.
|
||||
|
||||
Installation uses English (`en-us`), enables updates, and uses `Display Level="None"`. No `Updates TargetVersion` is set, so installation selection does not freeze future updates. The [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options) describes these settings. Existing update policies can subsequently override the chosen channel.
|
||||
|
||||
@@ -134,14 +136,13 @@ The helper, lock, and reinstall marker for these previously agreed logon tasks l
|
||||
|
||||
## Temporary media and cleanup during deployment
|
||||
|
||||
- A completed staging pass records a protected `media-cache.json` inventory with file sizes, version, original creation time, and matching product, architecture, channel, language, Windows 10 target (when applicable), and companion download definitions. Compatible runs move these installers into their new workspace instead of copying or redownloading them. This keeps each deployment's user cleanup ID separate. Company, activation, shutdown, and reboot selections are applied to freshly generated XML. The receipt reports `CachedMediaReused`. The new cache format refreshes caches created by older script versions once; subsequent matching validation/deployment runs reuse them normally.
|
||||
- Downloads live under `EmberkomOfficeDeployment\<deployment-id>` in `[IO.Path]::GetTempPath()` for the execution account. In Syncro this is SYSTEM's temp location, not the signed-in user's temp directory. The actual path is reported in `Workspace`. Folder permissions prevent standard users from changing executable content.
|
||||
- Cached installers remain eligible for reuse for **seven days**, provided the files still exist. This is a freshness limit, not a scheduled deletion policy. Expired, incomplete, unsigned, or incompatible caches are not reused. Size checks detect truncation, not same-size payload changes; the script leaves payload integrity checking to Microsoft's installer. Changing to a no-Teams plan cannot reuse a Teams-enabled cache. A failed deployment or a stop for restart leaves media in temp for a retry. Repeated validation does not extend the original freshness limit. If routine temp cleanup purges it first, the next run downloads fresh media.
|
||||
- Once Office and all selected companion apps are verified installed, the same script run deletes its entire temporary workspace, including the Office payload, ODT package/extraction, companion bootstrappers, cache manifest, helper copy, generated XML, and temporary process logs. It also removes unused older temporary deployment workspaces and known installer downloads from older ProgramData stages. Deferred-user files in ProgramData, installed applications, and Microsoft's servicing caches are preserved.
|
||||
- There is **no daily housekeeping task, resident housekeeping script, or separate log-retention job**. Validation/failure leftovers are subject to the endpoint's existing temp-cleanup routines; exact deletion timing depends on those routines. File removal rejects junctions/symlinks and skips workspaces referenced by running processes.
|
||||
- Cleanup failures do not change a verified installation into an installation failure. `ArtifactCleanupPending=true` and a console warning identify files left behind; there is no scheduled retry. A later successful deployment or the endpoint's ordinary temp cleanup can remove them.
|
||||
|
||||
Earlier ProgramData caches are not searched for reuse in the new temp location. Their known installer files are still cleaned after a successful deployment, while existing user helpers and diagnostic files are preserved. An RMM hard termination can interrupt cleanup; leftovers remain in temp rather than depending on a new background process.
|
||||
- Each actual installation uses a fresh protected `EmberkomOfficeDeployment\<deployment-id>` directory in the execution account's `[IO.Path]::GetTempPath()`. Under SYSTEM this can be `C:\Windows\SystemTemp`. There is no persistent media cache, manifest creation, or reuse across runs.
|
||||
- `finally` attempts to delete only downloaded Office/ODT payloads, companion bootstrappers and the temporary helper copy on successful installation, failed download/install, and early restart exits. Installation diagnostics, options, XML and locks remain for troubleshooting.
|
||||
- Before deleting any media, cleanup rejects links, inventories processes, and probes all candidate files for exclusive access. Active installers or processes referencing the workspace defer cleanup. Process-inventory failures also retain the files.
|
||||
- Successful install receipts include `MediaDownloaded=true`. `ArtifactCleanupPending=true` flags deferred/failed media cleanup on returned install/restart receipts. Cleanup errors are logged without replacing the original installation error or exit code.
|
||||
- Deferred per-user helpers remain in their separate ProgramData workspace while tasks still need them. Only a completed installation with no remaining helper tasks or processes can remove that helper workspace.
|
||||
- Hard RMM termination or power loss can bypass `finally`. The `OfficeStaging` category in `Start-SystemCleanup.ps1` reports/removes recognized abandoned media after `CleanupTempDays` (default seven days), including previous versions' cached downloads. It checks execution/profile temp, Windows Temp/SystemTemp and legacy ProgramData roots while holding the same deployment mutex. Run it first to reclaim old staging space before an installation that fails the free-space check.
|
||||
- No scheduled housekeeping job is created. Generic temp cleanup excludes the reserved `EmberkomOfficeDeployment` subtree; the dedicated category preserves logs, configuration, helper/task state and unknown files.
|
||||
|
||||
## Results and troubleshooting
|
||||
|
||||
@@ -162,7 +163,7 @@ If machine companion removal still fails verification, the error identifies the
|
||||
|
||||
The main script uses the overridden `Write-Output` and `Write-Error` from `Tools.ps1` for actions, retries, failures, and the final receipt, writing to its existing `$Global:LogFile`. Internal action messages suppress the logger's echoed success output to keep function results separate from diagnostics. The mode notice, log location, and final receipt use `Microsoft.PowerShell.Utility\Write-Output` for Syncro. Errors are logged and also printed to Syncro. Native PowerShell relaunch reloads Tools and restores the caller's log path. Run the core through the shim/Tools execution context, not as an independent file without Tools.
|
||||
|
||||
Process stdout/stderr logs, options, and generated XML are temporary files in the reported `Workspace`. They remain after a failed or validation-only run until a later successful deployment or routine temp cleanup removes them; they are deleted after successful installation. ODT removal uses `office-remove.stdout.log` / `.stderr.log` and `remove.xml`; installation uses `office-install.stdout.log` / `.stderr.log` and `install.xml`. The main Tools log retains the actions, results, and receipt and is not deleted. The separate limited-user cleanup task does not share the elevated Tools execution context; its small transcript remains in `%LOCALAPPDATA%\Emberkom\OfficeDeployment\<deployment-id>.log` for each user. Do not manually delete `UserCleanupWorkspace` while its logon tasks are pending.
|
||||
Process stdout/stderr logs, options, and generated XML are temporary files in the reported `Workspace`. They remain after installation attempts for troubleshooting; validation creates no staging workspace. Neither payload cleanup nor the dedicated OfficeStaging category deletes these small diagnostic files. ODT removal uses `office-remove.stdout.log` / `.stderr.log` and `remove.xml`; installation uses `office-install.stdout.log` / `.stderr.log` and `install.xml`. The main Tools log retains the actions, results, and receipt and is not deleted. The separate limited-user cleanup task does not share the elevated Tools execution context; its small transcript remains in `%LOCALAPPDATA%\Emberkom\OfficeDeployment\<deployment-id>.log` for each user. Do not manually delete `UserCleanupWorkspace` while its logon tasks are pending.
|
||||
|
||||
The separate legacy `Uninstall-MicrosoftOffice.ps1` deletes its downloaded VBS in `finally`, including after a failed/partial download or launch error. It is not part of the modern installer workflow. Registry-only Office fixes do not stage installers, and RMM shims execute their downloaded PowerShell source in memory.
|
||||
|
||||
@@ -170,7 +171,7 @@ The installer verifies the selected Office product, bitness, and downloaded vers
|
||||
|
||||
## Verification
|
||||
|
||||
Run `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\Install-MicrosoftOffice365.Tests.ps1` for offline checks. They require Windows PowerShell 5.1 and exercise the default validation gate (including `Force`), explicit deployment opt-out, log/console routing with the real Tools helpers, XML, removal-result handling, bounded cache deletion, companion installer failures/verification, deferred cleanup protection, and the unchanged `Run-Script` receiving injected strings through the shim with a mocked workload. Recovery checks simulate busy MSI, delayed registration, transient downloads, Appx removal races, persistent failures, and completed-task housekeeping errors. ODT removal tests cover silent XML, absent Office, mixed MSI/Click-to-Run installations, leftovers, read errors, MSI verification after installation, restart results, and absence of an interactive fallback. An inert executable checks actual native argument passing; a 32-bit Windows PowerShell child checks relaunch into 64-bit Windows PowerShell 5.1 and exit-code propagation. Tests use a separate mutex and do not run Microsoft installers or clear actual credentials.
|
||||
Run `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\Install-MicrosoftOffice365.Tests.ps1` for offline checks. They require Windows PowerShell 5.1 and exercise the default validation gate (including `Force`), explicit deployment opt-out, log/console routing with the real Tools helpers, XML, removal-result handling, bounded artifact deletion on success/failure/restart, metadata removal, active-process and locked-file protection, companion installer failures/verification, deferred cleanup protection, and the unchanged `Run-Script` receiving injected strings through the shim with a mocked workload. Recovery checks simulate busy MSI, delayed registration, transient downloads, Appx removal races, persistent failures, and completed-task housekeeping errors. ODT removal tests cover silent XML, absent Office, mixed MSI/Click-to-Run installations, leftovers, read errors, MSI verification after installation, restart results, and absence of an interactive fallback. An inert executable checks actual native argument passing; a 32-bit Windows PowerShell child checks relaunch into 64-bit Windows PowerShell 5.1 and exit-code propagation. Tests use a separate mutex and do not run Microsoft installers or clear actual credentials.
|
||||
|
||||
`Run-Script` is unchanged. Its existing local execution can read the Syncro variables from the enclosing caller scope. The Office workload validates those values and reports its own result and exit code. The shim only sets TLS, dot-sources `Tools.ps1`, and invokes the workload. Existing `Run-Script` bootstrap failure behavior also remains unchanged.
|
||||
|
||||
|
||||
+24
-3
@@ -120,10 +120,11 @@ selections, and mixtures of presets with other values also fail before cleanup.
|
||||
| Variable | Default | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `CleanupReportOnly` | true | Assess all categories versus apply enabled categories only |
|
||||
| `CleanupTempDays` | 7 | Temp files, installers, browser cache, Apple downloads |
|
||||
| `CleanupTempDays` | 7 | Temp files, installers, abandoned Office staging, browser cache, Apple downloads |
|
||||
| `CleanupDiagnosticDays` | 30 | CBS, WER archives, dumps, Revit journals |
|
||||
| `CleanupBackupDays` | 30 | Downloads, backups, time spent in Recycle Bin |
|
||||
| `CleanupSystemTemp` | true | Windows Temp, including EVTX, misc logs, AppxErrorReport, Chocolatey |
|
||||
| `CleanupSystemTemp` | true | Windows Temp and SystemTemp, including EVTX, misc logs, AppxErrorReport, Chocolatey; excludes Office staging |
|
||||
| `CleanupOfficeStaging` | true | Recognized abandoned Office deployment media, using CleanupTempDays; preserves diagnostics and deferred-user helpers |
|
||||
| `CleanupUserTemp` | true | Registered user profiles' Local Temp; AutoCAD `.ac$` only with AutoCAD closed |
|
||||
| `CleanupServiceTemp` | true | LocalService, NetworkService, SYSTEM profile temp folders |
|
||||
| `CleanupCBSArchives` | true | `CbsPersist_*.log` and `CbsPersist_*.cab` |
|
||||
@@ -218,6 +219,22 @@ termination can leave a temporary slot behind; future runs skip occupied slots.
|
||||
|
||||
## Deletion and operational boundaries
|
||||
|
||||
- `OfficeStaging` checks the execution account's temp directory, Windows Temp and
|
||||
SystemTemp, registered user/service profile temp directories, and legacy
|
||||
ProgramData, under `EmberkomOfficeDeployment`. It runs on clients and servers.
|
||||
The deployment mutex must be available, process inventory must succeed, and no
|
||||
recognized installer may be running. Each workspace must have a GUID name and a
|
||||
bounded, recognizable `options.json`; its directory, identity and every payload
|
||||
artifact must be older than `CleanupTempDays`. Recent, linked, locked, unrecognized
|
||||
or process-referenced workspaces are retained, including in report-only estimates.
|
||||
- Office cleanup deletes only named payload artifacts (ODT, companion installers,
|
||||
old GetHelp downloads and cache manifests). It preserves logs, options, XML,
|
||||
helper scripts, locks, task markers, unknown files and the workspace itself.
|
||||
Generic temp scans exclude this subtree, so they cannot bypass the dedicated
|
||||
option, retention or active-deployment checks. Report-only lists eligible media
|
||||
even when `CleanupOfficeStaging=false`; apply skips that disabled category.
|
||||
Process and mutex skips remain visible in the compact report; per-folder
|
||||
retention reasons are available through verbose output.
|
||||
- Inspect each file's modification time; an old parent never authorizes deletion
|
||||
of newer children. Ordinary cache/temp directories are retained.
|
||||
- Use literal local paths, verify containment, and skip reparse points and linked
|
||||
@@ -262,13 +279,17 @@ Coverage includes disabled-category estimates, separate report groups, unique
|
||||
totals for overlapping categories, and disabled categories remaining untouched in
|
||||
apply mode. Preset tests verify exact handler membership, cumulative selections,
|
||||
RMM scope preservation, None disabling native work, and the server exclusions.
|
||||
Output tests cover the duplicate-object regression, a 22-category preview under
|
||||
Output tests cover the duplicate-object regression, a 23-category preview under
|
||||
4 KiB including diagnostics, separate enabled/disabled sections, and preservation
|
||||
of diagnostic notes. Regression checks ensure DISM analysis is absent and report
|
||||
diagnostics launch no native programs.
|
||||
Hibernation/VSS tests cover usage in category MiB columns, zero for absence,
|
||||
unknown sizes after access failures, cross-drive storage, server exclusions, no
|
||||
duplicate diagnostic lines, and usage staying out of savings totals.
|
||||
Office staging tests cover Windows SystemTemp and legacy ProgramData, complete
|
||||
artifact selection, identity/age/link/lock/process guards, deployment mutex
|
||||
contention, disabled categories, server support, generic-temp exclusion, and
|
||||
preservation of diagnostics and deferred-user files.
|
||||
|
||||
References: [OS ProductType](https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-operatingsystem),
|
||||
[Disk Cleanup](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cleanmgr),
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
# See docs/Office365-Deployment.md.
|
||||
# Configure these [string] Dropdown variables in Syncro:
|
||||
# [string]$ValidateBeforeChanges - true (default: validate only), false (remove/reinstall)
|
||||
# Validation checks prerequisites and small release metadata; it downloads no installation media.
|
||||
# Install mode downloads before uninstalling and cleans media on success/failure/restart exits.
|
||||
# Logs and pending per-user cleanup helpers are retained; active installers defer media cleanup.
|
||||
# [string]$OfficeSubscription - Required; use the exact subscription names in the guide.
|
||||
# [string]$OfficeArchitecture - Auto (default), 64, 32
|
||||
# [string]$UpdateChannel - Current (default), MonthlyEnterprise, SemiAnnual
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# Configure these [string] Dropdown variables in Syncro, each with true/false choices:
|
||||
# [string]$CleanupReportOnly - true (default: assess all), false (apply enabled only)
|
||||
# [string]$CleanupSystemTemp - true (default), false
|
||||
# [string]$CleanupOfficeStaging - true (default), false; uses CleanupTempDays
|
||||
# [string]$CleanupUserTemp - true (default), false
|
||||
# [string]$CleanupServiceTemp - true (default), false
|
||||
# [string]$CleanupCBSArchives - true (default), false
|
||||
@@ -48,6 +49,8 @@
|
||||
# Verbose output can exceed Syncro's output limit. No new Syncro variables are needed.
|
||||
# Server-blocked categories are listed without assessment. Native savings may be unknown.
|
||||
# Server exclusions cannot be overridden by these variables. No reboot is initiated.
|
||||
# OfficeStaging checks Windows Temp/SystemTemp, execution/profile temp and legacy ProgramData.
|
||||
# Only recognized, aged installer media is eligible; active deployments and user helpers are protected.
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
|
||||
@@ -350,7 +350,7 @@ try {
|
||||
if ([IO.Path]::GetFileName($Path) -eq 'odt-download-page.html') {
|
||||
Assert-OfficeTest ($TimeoutSeconds -eq (Get-OfficeDeploymentDefinitions).OdtPageTimeoutSeconds) 'ODT page must use the retried downloader with its configured timeout.'
|
||||
[IO.File]::WriteAllText($Path, 'https://download.microsoft.com/test/officedeploymenttool_test.exe')
|
||||
} elseif ([IO.Path]::GetFileName($Path) -eq 'office-release-history.html') {
|
||||
} elseif ($Uri -eq (Get-OfficeDeploymentDefinitions).OfficeReleaseHistory) {
|
||||
Assert-OfficeTest ($Uri -eq (Get-OfficeDeploymentDefinitions).OfficeReleaseHistory) 'Windows 10 release lookup must use Microsoft history.'
|
||||
[IO.File]::WriteAllText($Path, $script:mediaHistory)
|
||||
} elseif ([IO.Path]::GetFileName($Path) -eq 'Office-UserCleanup.ps1') {
|
||||
@@ -833,86 +833,27 @@ try {
|
||||
Assert-OfficeTest ((Get-Content -LiteralPath $Global:LogFile -Raw) -match 'Error: User cleanup task registration failed for unmapped \(C:\\Users\\defaultuser100000\)') 'Registration failures must reach the Tools diagnostic log.'
|
||||
}
|
||||
|
||||
# Real temporary files for cache reuse/completeness; no installer or network may run.
|
||||
# Validation can resolve small release metadata without keeping it or staging media.
|
||||
& {
|
||||
$cacheRoot = Join-Path $testRoot 'cache-tests'; $null = [IO.Directory]::CreateDirectory($cacheRoot)
|
||||
$source = Join-Path $cacheRoot ('a' * 32); $null = [IO.Directory]::CreateDirectory($source)
|
||||
# LiteralPath matters: the staged fixture intentionally contains brackets.
|
||||
foreach ($file in Get-ChildItem -LiteralPath (Join-Path $testRoot 'media [literal]')) { Copy-Item -LiteralPath $file.FullName -Destination $source -Recurse }
|
||||
$target = Join-Path $cacheRoot ('b' * 32); $null = [IO.Directory]::CreateDirectory($target)
|
||||
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeArchitecture='64'; COMPANY='New Company'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'}
|
||||
$script:rejectCacheSignature = $false; $script:helperDownloads = 0
|
||||
function Get-CimInstance { }
|
||||
function Assert-OfficeDiskSpace { throw 'Cache reuse must not request fresh-download disk reserve; the main workflow checks installation space afterward.' }
|
||||
function Assert-OfficeMicrosoftSignature { param($Path) if ($script:rejectCacheSignature) { throw 'Untrusted cache signature' }; Assert-OfficeTest (Test-Path -LiteralPath $Path) 'Cache signature target was missing.' }
|
||||
function Save-OfficeDownload { param($Uri,$Path) if ([IO.Path]::GetFileName($Path) -ne 'Office-UserCleanup.ps1') { throw 'Unexpected network download on cache hit' }; $script:helperDownloads++; Set-Content -LiteralPath $Path -Value ('# ' + (Get-OfficeDeploymentDefinitions).HelperVersion) }
|
||||
function Invoke-OfficeProcess { throw 'A cached deployment must not redownload Office.' }
|
||||
$manifestPath = Join-Path $source 'media-cache.json'
|
||||
$originalManifest = Get-Content -LiteralPath $manifestPath -Raw
|
||||
Assert-OfficeTest (!($originalManifest | ConvertFrom-Json).Files[0].PSObject.Properties['Hash']) 'Cache manifests must not store file checksums.'
|
||||
$different = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5'; OfficeArchitecture='64'}
|
||||
Assert-OfficeTest (!(Restore-OfficeMediaCache $different $target)) 'Teams selection mismatch reused the wrong cache.'
|
||||
$different = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeArchitecture='64'; UpdateChannel='MonthlyEnterprise'}
|
||||
Assert-OfficeTest (!(Restore-OfficeMediaCache $different $target)) 'Channel mismatch reused the wrong cache.'
|
||||
$different = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeArchitecture='64'}
|
||||
$different.TargetOfficeVersion='16.0.20326.20158'
|
||||
Assert-OfficeTest (!(Restore-OfficeMediaCache $different $target)) 'A Windows 10 target reused incompatible unpinned media.'
|
||||
$manifest = $originalManifest | ConvertFrom-Json; $manifest.Key = Get-OfficeMediaCacheKey $different
|
||||
$manifest | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $manifestPath
|
||||
Assert-OfficeTest (!(Restore-OfficeMediaCache $different $target)) 'A matching cache key hid an incompatible Windows 10 payload version.'
|
||||
$manifest = $originalManifest | ConvertFrom-Json; $manifest.Schema = 1
|
||||
$manifest | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $manifestPath
|
||||
Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Old cache manifests must be refreshed under the new version-selection contract.'
|
||||
$manifest = $originalManifest | ConvertFrom-Json; $manifest.CreatedUtc = [DateTime]::UtcNow.AddDays(-8).ToString('o')
|
||||
$manifest | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $manifestPath
|
||||
Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Expired cache was reused.'
|
||||
Set-Content -LiteralPath $manifestPath -Value $originalManifest
|
||||
$stream = Join-Path $source 'ODT\Office\Data\16.0.12345.67890\stream.x64.x-none.dat'
|
||||
$originalBytes = [IO.File]::ReadAllBytes($stream); [IO.File]::WriteAllText($stream, '')
|
||||
Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Truncated cached media passed the basic size check.'
|
||||
[IO.File]::WriteAllBytes($stream, $originalBytes)
|
||||
$extra = Join-Path $source 'ODT\unexpected.dll'; Set-Content -LiteralPath $extra -Value 'unexpected dependency'
|
||||
Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Unrecorded executable dependencies passed cache verification.'
|
||||
Remove-OfficeManagedItem $cacheRoot $extra
|
||||
function Get-CimInstance { [pscustomobject]@{CommandLine="setup.exe $source\install.xml"} }
|
||||
Assert-OfficeThrows { Restore-OfficeMediaCache $options $target } 'previous Office deployment still has active processes'
|
||||
Assert-OfficeTest (Test-Path -LiteralPath $stream) 'A live installer lost its cached media.'
|
||||
function Get-CimInstance { }
|
||||
$script:rejectCacheSignature = $true
|
||||
Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Invalid Microsoft signature was reused.'
|
||||
$script:rejectCacheSignature = $false
|
||||
# Same-size contents are deliberately not hashed; ODT services the payload.
|
||||
$changedBytes = $originalBytes.Clone(); $changedBytes[0] = $changedBytes[0] -bxor 1; [IO.File]::WriteAllBytes($stream, $changedBytes)
|
||||
$media = Initialize-OfficeMedia $options $target
|
||||
Assert-OfficeTest ($media.CachedMediaReused -and $media.Version -eq '16.0.12345.67890' -and $script:helperDownloads -eq 1) 'Deployment did not reuse the validated media and refresh the helper.'
|
||||
Assert-OfficeTest (!(Test-Path -LiteralPath (Join-Path $source 'ODT')) -and (Test-Path -LiteralPath $media.Setup)) 'Cache transfer duplicated large files or lost setup.'
|
||||
$config = [xml](Get-Content -LiteralPath $media.Config -Raw)
|
||||
Assert-OfficeTest ($config.Configuration.AppSettings.Setup.Value -eq 'New Company' -and $config.Configuration.Add.SourcePath -eq (Join-Path $target 'ODT')) 'Reused media retained stale company/configuration paths.'
|
||||
Assert-OfficeTest (!$config.Configuration.Add.HasAttribute('Version')) 'Reusing ordinary media must not pin the installation version.'
|
||||
Assert-OfficeTest ((Get-Content -LiteralPath (Join-Path $target 'media-cache.json') -Raw | ConvertFrom-Json).CreatedUtc -eq ($originalManifest | ConvertFrom-Json).CreatedUtc) 'Reuse extended cache expiry.'
|
||||
Assert-OfficeThrows { Remove-OfficeManagedItem $cacheRoot $testRoot } 'outside the Office deployment root'
|
||||
Assert-OfficeThrows { Remove-OfficeManagedItem $cacheRoot $cacheRoot } 'outside the Office deployment root'
|
||||
|
||||
# Windows 10 refreshes only the small release history and helper on a compatible hit.
|
||||
$win10Source = Join-Path $cacheRoot ('c' * 32); $null = [IO.Directory]::CreateDirectory($win10Source)
|
||||
foreach ($file in Get-ChildItem -LiteralPath (Join-Path $testRoot 'win10')) { Copy-Item -LiteralPath $file.FullName -Destination $win10Source -Recurse }
|
||||
$win10Target = Join-Path $cacheRoot ('d' * 32); $null = [IO.Directory]::CreateDirectory($win10Target)
|
||||
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Standard'; OfficeArchitecture='64'}
|
||||
$options.OfficeFeatureRelease = Get-OfficeFeatureRelease -Build 19045 -ProductType 1
|
||||
$script:historyPaths=@()
|
||||
function Save-OfficeDownload {
|
||||
param($Uri,$Path)
|
||||
switch ([IO.Path]::GetFileName($Path)) {
|
||||
'office-release-history.html' { [IO.File]::WriteAllText($Path, $releaseHistory) }
|
||||
'Office-UserCleanup.ps1' { [IO.File]::WriteAllText($Path, '# ' + (Get-OfficeDeploymentDefinitions).HelperVersion) }
|
||||
default { throw 'Unexpected installer download on Windows 10 cache hit' }
|
||||
Assert-OfficeTest ($Uri -eq (Get-OfficeDeploymentDefinitions).OfficeReleaseHistory) 'Preflight fetched installer media.'
|
||||
$script:historyPaths += $Path
|
||||
[IO.File]::WriteAllText($Path,$script:historyFixture)
|
||||
}
|
||||
$options=Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'}
|
||||
Resolve-OfficeTargetVersion $options
|
||||
Assert-OfficeTest ($script:historyPaths.Count -eq 0 -and !$options.TargetOfficeVersion) 'Unpinned preflight must not download release metadata.'
|
||||
$options.OfficeFeatureRelease='2608'; $script:historyFixture=$releaseHistory
|
||||
Resolve-OfficeTargetVersion $options
|
||||
Assert-OfficeTest ($options.TargetOfficeVersion -eq '16.0.20326.20158' -and !(Test-Path -LiteralPath $script:historyPaths[-1])) 'Resolved metadata must be removed after successful preflight.'
|
||||
$script:historyFixture='<html>No build</html>'
|
||||
Assert-OfficeThrows { Resolve-OfficeTargetVersion $options } 'did not identify'
|
||||
Assert-OfficeTest (!(Test-Path -LiteralPath $script:historyPaths[-1])) 'Failed preflight retained release metadata.'
|
||||
}
|
||||
$media = Initialize-OfficeMedia $options $win10Target
|
||||
Assert-OfficeTest ($media.CachedMediaReused -and $media.Version -eq '16.0.20326.20158') 'Windows 10 did not reuse compatible validated media.'
|
||||
Assert-OfficeTest (([xml](Get-Content -LiteralPath $media.Config -Raw)).Configuration.Add.Version -eq $media.Version) 'Reused Windows 10 media lost its compatible version constraint.'
|
||||
}
|
||||
# Cleanup runs synchronously on success. Downloads are temporary; pending-user
|
||||
# helpers have a separate durable folder and are never part of the media cache.
|
||||
# Cleanup runs synchronously on every install exit. Downloads are temporary; pending-user
|
||||
# helpers have a separate durable folder and are never part of disposable media.
|
||||
& {
|
||||
$root = Join-Path $testRoot 'temporary-downloads'; $null = [IO.Directory]::CreateDirectory($root)
|
||||
$workspace = Join-Path $root ('c' * 32); $null = [IO.Directory]::CreateDirectory($workspace)
|
||||
@@ -929,7 +870,7 @@ try {
|
||||
}
|
||||
$media = [pscustomobject]@{Helper=(Join-Path $workspace 'Office-UserCleanup.ps1')}
|
||||
$userWorkspace = New-OfficeUserWorkspace $media $workspace
|
||||
Assert-OfficeTest ($media.Helper -eq (Join-Path $userWorkspace 'Office-UserCleanup.ps1') -and (Test-Path -LiteralPath $media.Helper)) 'User helper was not separated from cached installers.'
|
||||
Assert-OfficeTest ($media.Helper -eq (Join-Path $userWorkspace 'Office-UserCleanup.ps1') -and (Test-Path -LiteralPath $media.Helper)) 'User helper was not separated from staged installers.'
|
||||
$script:cleanupTasks = $true; $script:cleanupProcess = $true
|
||||
function Get-CimInstance { if ($script:cleanupProcess) { [pscustomobject]@{CommandLine="setup.exe $workspace\install.xml"} } }
|
||||
function Get-ScheduledTask { if ($script:cleanupTasks) { [pscustomobject]@{TaskName="Emberkom-OfficeCleanup-$('c' * 32)-SID"; State='Ready'} } }
|
||||
@@ -938,16 +879,24 @@ try {
|
||||
Assert-OfficeTest ($warnings.Count -and (Test-Path -LiteralPath (Join-Path $workspace 'ODT'))) 'Cleanup deleted files referenced by a surviving installer.'
|
||||
$script:cleanupProcess = $false
|
||||
$warnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace
|
||||
Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath $workspace)) 'Successful deployment left its temporary workspace behind.'
|
||||
Assert-OfficeTest (Test-Path -LiteralPath $media.Helper) 'Temporary cache cleanup deleted the pending-user helper.'
|
||||
Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath (Join-Path $workspace 'ODT')) -and !(Test-Path -LiteralPath (Join-Path $workspace 'odt.exe')) -and (Test-Path -LiteralPath (Join-Path $workspace 'office-install.stdout.log'))) 'Completion must remove media and preserve diagnostics.'
|
||||
Assert-OfficeTest (Test-Path -LiteralPath $media.Helper) 'Temporary media cleanup deleted the pending-user helper.'
|
||||
$script:cleanupTasks = $false
|
||||
$warnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace
|
||||
Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath $userWorkspace)) 'Completed user cleanup left its helper folder behind.'
|
||||
# Older ProgramData stages lose only known downloads, never deferred-user files.
|
||||
$legacy = Join-Path $userRoot ('d' * 32); $null = [IO.Directory]::CreateDirectory($legacy)
|
||||
foreach ($name in @('options.json','odt.exe','Office-UserCleanup.ps1','user-cleanup.lock')) { Set-Content -LiteralPath (Join-Path $legacy $name) -Value 'fixture' }
|
||||
$warnings = Complete-OfficeDeploymentFiles $workspace -PreviousRoot $userRoot
|
||||
Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath (Join-Path $legacy 'odt.exe')) -and (Test-Path -LiteralPath (Join-Path $legacy 'Office-UserCleanup.ps1'))) 'Legacy download cleanup lost pending-user state or left old downloads.'
|
||||
# An installer without a source path, locked media and links all defer cleanup.
|
||||
Assert-OfficeTest (Test-OfficeStagingInUse $workspace @([pscustomobject]@{Name='OfficeC2RClient.exe'})) 'Surviving native installers must defer media cleanup.'
|
||||
Assert-OfficeThrows { Remove-OfficeManagedItem $root $testRoot } 'outside the Office deployment root'
|
||||
Assert-OfficeThrows { Remove-OfficeManagedItem $root $root } 'outside the Office deployment root'
|
||||
$payload=Join-Path $workspace 'odt.exe'; [IO.File]::WriteAllText($payload,'locked')
|
||||
$handle=[IO.File]::Open($payload,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::None)
|
||||
try {
|
||||
$warnings=Complete-OfficeDeploymentFiles $workspace
|
||||
Assert-OfficeTest ($warnings.Count -gt 0 -and (Test-Path -LiteralPath $payload)) 'In-use payload must survive final cleanup.'
|
||||
} finally { $handle.Dispose() }
|
||||
function Get-CimInstance { throw 'Synthetic process inventory failure' }
|
||||
$warnings=Complete-OfficeDeploymentFiles $workspace
|
||||
Assert-OfficeTest ($warnings.Count -gt 0 -and (Test-Path -LiteralPath $payload)) 'Unknown process state must retain media.'
|
||||
}
|
||||
# The legacy uninstaller must delete both successful and partial downloads.
|
||||
& {
|
||||
@@ -973,11 +922,12 @@ try {
|
||||
throw "Unexpected object requested by orchestration fixture: $TypeName"
|
||||
}
|
||||
function Assert-OfficeDeploymentHost { }
|
||||
function Assert-OfficeDiskSpace { param($Workspace,[switch]$DownloadingMedia) if ($script:mode -eq 'disk-space') { throw 'Insufficient disk space after staging' } }
|
||||
function Complete-OfficeDeploymentFiles { param($Workspace,$UserWorkspace,$PreviousRoot) $script:artifactCleanupRuns++; if ($script:mode -eq 'cleanup-warning') { return ,@('Synthetic file in use') }; return ,@() }
|
||||
function Assert-OfficeDiskSpace { param($Workspace,[switch]$DownloadingMedia) if ($script:mode -eq 'preflight-space') { throw 'Insufficient disk space before download' }; if ($script:mode -eq 'disk-space' -and !$DownloadingMedia) { throw 'Insufficient disk space after staging' } }
|
||||
function Resolve-OfficeTargetVersion { if ($script:mode -eq 'release') { throw 'Release metadata unavailable' } }
|
||||
function Complete-OfficeDeploymentFiles { param($Workspace,$UserWorkspace) $script:artifactCleanupRuns++; if ($script:mode -eq 'download-cleanup') { throw 'Synthetic cleanup failure' }; if ($script:mode -eq 'cleanup-warning') { return ,@('Synthetic file in use') }; return ,@() }
|
||||
function New-OfficeUserWorkspace { param($Media,$Workspace) $Workspace }
|
||||
function Register-ScheduledTask { throw 'Unexpected task registration in orchestration fixture.' }
|
||||
function New-OfficeWorkspace { $path = Join-Path $testRoot ([guid]::NewGuid().ToString('N')); $null = New-Item -ItemType Directory -Path $path; $path }
|
||||
function New-OfficeWorkspace { $script:workspaceCreates++; $path = Join-Path $testRoot ([guid]::NewGuid().ToString('N')); $null = New-Item -ItemType Directory -Path $path; $path }
|
||||
function Start-Transcript { }
|
||||
function Stop-Transcript { }
|
||||
function Get-CimInstance { [pscustomobject]@{SID='S-1-5-21-test'; LocalPath=$profile; Special=$false} }
|
||||
@@ -986,7 +936,7 @@ try {
|
||||
function Get-OfficeRunningApps { }
|
||||
function Get-OfficeSuiteInventory { if ($script:mode -ne 'office-reboot' -or $script:removalStillRegistered) { [pscustomobject]@{DisplayName='Synthetic Office'} } }
|
||||
function Get-OfficeMachineCompanionEntries { if ($script:removalStillRegistered) { [pscustomobject]@{DisplayName='Synthetic OneDrive'} } }
|
||||
function Initialize-OfficeMedia { param($Options,$Workspace) $script:events += 'download'; if ($script:mode -eq 'download') { throw 'download failure' }; [pscustomobject]@{Version='16.0.1.2'; Helper=(Join-Path $Workspace 'Office-UserCleanup.ps1')} }
|
||||
function Initialize-OfficeMedia { param($Options,$Workspace) $script:events += 'download'; if ($script:mode -in @('download','download-cleanup')) { throw 'download failure' }; [pscustomobject]@{Version='16.0.1.2'; Helper=(Join-Path $Workspace 'Office-UserCleanup.ps1')} }
|
||||
function Remove-OfficeCompanionApps { $script:events += 'companions'; if ($script:mode -eq 'companions') { throw 'companion failure' }; return ($script:mode -eq 'reboot') }
|
||||
function Remove-OfficeSuite { $script:events += 'remove-office'; if ($script:mode -eq 'remove-office') { throw 'Office removal failure' }; if ($script:mode -eq 'office-reboot') { return 3010 }; return 0 }
|
||||
function Clear-OfficeProfileIdentity { $script:events += 'identity'; if ($script:mode -eq 'identity') { throw 'identity failure' } }
|
||||
@@ -1002,7 +952,7 @@ try {
|
||||
function Install-OfficeCompanionApps { param($Media,$Workspace,[bool]$InstallTeams) $script:teamsRequested=$InstallTeams; $script:events += 'install-companions'; if ($script:mode -eq 'install-companions') { throw 'companion install failure' }; [pscustomobject]@{ExitCode=$(if ($script:mode -eq 'companion-reboot') {3010} else {0}); Versions=@{NewOutlook='1'; OneDrive='1'}} }
|
||||
$script:removalStillRegistered=$false
|
||||
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'; DeferReboot='false'}
|
||||
foreach ($script:mode in @('success','download','disk-space','companions','remove-office','identity','user','phase','install','install-companions','pending','reboot','office-reboot','companion-reboot')) {
|
||||
foreach ($script:mode in @('success','download','download-cleanup','disk-space','companions','remove-office','identity','user','phase','install','install-companions','pending','reboot','office-reboot','companion-reboot')) {
|
||||
$script:artifactCleanupRuns = 0
|
||||
$script:events = @(); $errorResult = $null; $result = $null
|
||||
try { $result = Invoke-OfficeDeployment $options } catch { $errorResult = $_ }
|
||||
@@ -1013,15 +963,19 @@ try {
|
||||
} else { Assert-OfficeTest ($null -ne $errorResult) "Failure swallowed in $script:mode" }
|
||||
if ($script:mode -notin @('success','pending','install','install-companions','companion-reboot')) { Assert-OfficeTest ('install' -notin $script:events) "Install ran after $script:mode failure/reboot." }
|
||||
if ($script:mode -notin @('success','pending','install-companions','companion-reboot')) { Assert-OfficeTest ('install-companions' -notin $script:events) "Companion install ran after $script:mode failure/reboot." }
|
||||
if ($script:mode -eq 'download') { Assert-OfficeTest ('companions' -notin $script:events -and 'remove-office' -notin $script:events) 'Removal ran after download failed.' }
|
||||
if ($script:mode -in @('download','download-cleanup')) { Assert-OfficeTest ('companions' -notin $script:events -and 'remove-office' -notin $script:events) 'Removal ran after download failed.' }
|
||||
if ($script:mode -eq 'download-cleanup') { Assert-OfficeTest ($errorResult.Exception.Message -eq 'download failure') 'Cleanup replaced the original deployment failure.' }
|
||||
if ($script:mode -eq 'disk-space') { Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Low space after staging must stop before app shutdown, removal, identity cleanup, and installation.' }
|
||||
Assert-OfficeTest ($script:artifactCleanupRuns -eq $(if ($script:mode -in @('success','pending','companion-reboot')) {1} else {0})) "Media cleanup ran before successful installation, or was skipped after success: $script:mode"
|
||||
Assert-OfficeTest ($script:artifactCleanupRuns -eq 1) "Finally must attempt media cleanup on every install exit: $script:mode"
|
||||
if ($script:mode -eq 'office-reboot') { Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'RestartRequiredBeforeInstall' -and 'identity' -notin $script:events -and 'user' -notin $script:events) 'Office removal restart must stop before user cleanup and replacement installation.' }
|
||||
if ($script:mode -eq 'success') { Assert-OfficeTest (($script:events -join ',') -eq 'download,apps,companions,remove-office,identity,user,phase,install,install-companions') 'Deployment order changed.' }
|
||||
}
|
||||
$script:mode='disk-space'; $script:events=@(); $options.ValidateBeforeChanges=$true
|
||||
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Insufficient disk space after staging'
|
||||
Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Validation must not report success or mutate apps with insufficient installation space.'
|
||||
$script:mode='preflight-space'; $script:events=@(); $options.ValidateBeforeChanges=$true; $script:workspaceCreates=0; $script:artifactCleanupRuns=0
|
||||
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Insufficient disk space before download'
|
||||
Assert-OfficeTest ($script:events.Count -eq 0 -and $script:workspaceCreates -eq 0 -and $script:artifactCleanupRuns -eq 0) 'Low-space validation must stop without staging or housekeeping.'
|
||||
$options.ValidateBeforeChanges=$false
|
||||
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Insufficient disk space before download'
|
||||
Assert-OfficeTest ($script:events.Count -eq 0 -and $script:workspaceCreates -eq 0) 'Low-space install must stop before creating a workspace.'
|
||||
$options.ValidateBeforeChanges=$false
|
||||
$script:mode='cleanup-warning'; $script:events=@()
|
||||
$result = @(Invoke-OfficeDeployment $options)
|
||||
@@ -1056,12 +1010,12 @@ try {
|
||||
Assert-OfficeTest (!$result.RestartRequired -and $result.ExitCode -eq 0) 'A clean deployment without restart requests must not demand a restart.'
|
||||
foreach ($shutdown in @('Abort','Force')) {
|
||||
foreach ($validate in @($null, '', 'true')) {
|
||||
$script:events=@()
|
||||
$script:events=@(); $script:workspaceCreates=0; $script:artifactCleanupRuns=0
|
||||
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeAppShutdown=$shutdown; ValidateBeforeChanges=$validate}
|
||||
$result = Invoke-OfficeDeployment $options
|
||||
Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'ValidationPassed' -and $result.ExitCode -eq 0 -and $result.ValidateBeforeChanges) 'Validation did not produce a distinct result.'
|
||||
Assert-OfficeTest ($result.OfficeRemovalMethod -eq 'SilentODT' -and $result.DeferReboot -is [bool] -and $result.DeferReboot) 'Validation must identify the silent removal method and Boolean restart selection.'
|
||||
Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Validation reached app shutdown, removal, identities, user tasks, phase changes, or installation.'
|
||||
Assert-OfficeTest ($script:events.Count -eq 0 -and $script:workspaceCreates -eq 0 -and $script:artifactCleanupRuns -eq 0 -and !$result.MediaDownloaded -and !$result.Workspace) 'Validation downloaded media, created a workspace or reached a deployment action.'
|
||||
Assert-OfficeTest (!$result.TeamsSelected -and $result.ProfileCount -eq 1 -and $result.ExistingOffice[0] -eq 'Synthetic Office') 'Validation report lost the deployment plan.'
|
||||
}
|
||||
}
|
||||
@@ -1069,13 +1023,13 @@ try {
|
||||
$script:events=@()
|
||||
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'}
|
||||
$result = Invoke-OfficeDeployment $options
|
||||
Assert-OfficeTest (($script:events -join ',') -eq 'download' -and $result.RunningApps[0] -eq 'winword') 'Validation closed a running app with Force selected.'
|
||||
Assert-OfficeTest ($script:events.Count -eq 0 -and $result.RunningApps[0] -eq 'winword') 'Validation downloaded media or closed a running app with Force selected.'
|
||||
$options.OfficeAppShutdown='Abort'; $script:events=@()
|
||||
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Apps are running'
|
||||
Assert-OfficeTest ($script:events.Count -eq 0) 'Validation did not stop on an Abort prerequisite failure.'
|
||||
$options.OfficeAppShutdown='Force'; $script:mode='download'; $script:events=@()
|
||||
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'download failure'
|
||||
Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Failed validation reached mutations.'
|
||||
$options.OfficeAppShutdown='Force'; $script:mode='release'; $script:events=@()
|
||||
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Release metadata unavailable'
|
||||
Assert-OfficeTest ($script:events.Count -eq 0) 'Failed validation reached media downloads or mutations.'
|
||||
$options.ValidateBeforeChanges='false'
|
||||
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'validated Boolean'
|
||||
$options.ValidateBeforeChanges=$false; $options.DeferReboot='false'; $script:events=@()
|
||||
|
||||
@@ -34,6 +34,8 @@ try {
|
||||
foreach ($definition in $core.FindAll({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst]}, $false)) {
|
||||
. ([scriptblock]::Create($definition.Extent.Text))
|
||||
}
|
||||
# Never contend with a real deployment on the test host.
|
||||
function New-SystemCleanupOfficeMutex { return [Threading.Mutex]::new($false) }
|
||||
$messageWriter = ${function:Write-SystemCleanupMessage}
|
||||
$script:messages = @(); $script:details = @()
|
||||
function Write-SystemCleanupMessage {
|
||||
@@ -209,7 +211,7 @@ try {
|
||||
$o.ReportOnly=$true
|
||||
foreach ($name in $blocked) { if ($name -ne 'DiskCleanup') { $o[$name]=$true } }
|
||||
$result = @(Invoke-SystemCleanup $o)
|
||||
Assert-Cleanup ($result.Count -eq 22 -and @($result | Where-Object Status -eq 'Blocked on server').Count -eq $blocked.Count) 'Server report must list every blocked category.'
|
||||
Assert-Cleanup ($result.Count -eq 23 -and @($result | Where-Object Status -eq 'Blocked on server').Count -eq $blocked.Count) 'Server report must list every blocked category.'
|
||||
Assert-Cleanup (@($script:assessed | Where-Object { $_ -in $blocked }).Count -eq 0) 'Server report must not assess blocked categories.'
|
||||
}
|
||||
|
||||
@@ -329,6 +331,96 @@ try {
|
||||
Assert-Cleanup ($d.Count -eq 0 -and $script:fileReads -eq 0 -and $script:storageReads -eq 0 -and $script:diagnosticProcesses -eq 0) 'Apply mode must not run report diagnostics.'
|
||||
}
|
||||
|
||||
# Abandoned Office payloads: report/apply, disabled options, server support,
|
||||
# identity, retention, process/lock/link protection, and durable helper survival.
|
||||
& {
|
||||
$officeAst=Read-CleanupAst 'Install-MicrosoftOffice365.ps1'
|
||||
foreach ($definition in $officeAst.FindAll({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -in @('Get-OfficeDeploymentDefinitions','Get-OfficeStagingNames')},$false)) {
|
||||
. ([scriptblock]::Create($definition.Extent.Text))
|
||||
}
|
||||
$names=@(Get-OfficeStagingNames)
|
||||
$script:officeProcesses=@(); $script:officeInventoryFails=$false
|
||||
function Get-CimInstance { if ($script:officeInventoryFails) { throw 'Synthetic process inventory failure' }; $script:officeProcesses }
|
||||
function New-StageFixture {
|
||||
param($Parent,$Id)
|
||||
$relative=$Parent+'\'+($Id*32)
|
||||
$null=New-CleanupFixture ($relative+'\options.json') '{"ProductId":"O365BusinessRetail","OfficeArchitecture":"64","UpdateChannel":"Current"}'
|
||||
foreach ($name in $names) {
|
||||
$leaf=if ($name -in @('ODT','GetHelp')) { $name+'\payload.dat' } else { $name }
|
||||
$null=New-CleanupFixture ($relative+'\'+$leaf)
|
||||
}
|
||||
foreach ($name in @('Office-UserCleanup.ps1','user-cleanup.lock','install.xml','office-install.stdout.log','unknown.exe')) { $null=New-CleanupFixture ($relative+'\'+$name) }
|
||||
$folder=Join-Path $testRoot $relative
|
||||
foreach ($dir in @(Get-ChildItem -LiteralPath $folder -Recurse -Directory)+@(Get-Item -LiteralPath $folder)) { [IO.Directory]::SetLastWriteTimeUtc($dir.FullName,[datetime]::UtcNow.AddDays(-60)) }
|
||||
return $folder
|
||||
}
|
||||
function Test-StageCleanup {
|
||||
param([bool]$ReportOnly=$true,[bool]$Enabled=$true,[bool]$Server=$false)
|
||||
$c=New-CleanupContext -ReportOnly $ReportOnly -Server $Server; $c.Options.OfficeStaging=$Enabled
|
||||
Invoke-SystemCleanupCategory $c 'OfficeStaging' { Clear-SystemCleanupOfficeStaging $c $stageRoots ([datetime]::UtcNow.AddDays(-7)) }
|
||||
return $c
|
||||
}
|
||||
$folder=New-StageFixture 'office-fixture\Windows\SystemTemp\EmberkomOfficeDeployment' 'a'
|
||||
$legacy=New-StageFixture 'office-fixture\ProgramData\EmberkomOfficeDeployment' 'b'
|
||||
$stageRoots=@((Split-Path -Parent $folder),(Split-Path -Parent $legacy))
|
||||
Assert-Cleanup ((Get-SystemCleanupOfficeStagingRoots @()) -contains (Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment')) 'SystemTemp must be a supported Office staging root.'
|
||||
$c=Test-StageCleanup -Enabled $false
|
||||
Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq (2*$names.Count) -and !$c.Stats.OfficeStaging.Enabled -and (Test-Path -LiteralPath (Join-Path $folder 'ODT\payload.dat'))) 'Disabled report must measure every installer artifact without deleting it.'
|
||||
$c=Test-StageCleanup -Server $true
|
||||
Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq (2*$names.Count) -and $c.Errors -eq 0) 'Owned staging cleanup must support server OSes.'
|
||||
$c=New-CleanupContext
|
||||
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' (Split-Path -Parent $stageRoots[0]) ([datetime]::UtcNow.AddDays(-7)) -Recurse }
|
||||
Assert-Cleanup ($c.Stats.SystemTemp.CandidateFiles -eq 0) 'Generic temp traversal must exclude Office staging entirely.'
|
||||
$c=Test-StageCleanup -ReportOnly $false -Enabled $false
|
||||
Assert-Cleanup ((Test-Path -LiteralPath (Join-Path $folder 'ODT\payload.dat')) -and !$c.Stats.Count) 'Disabled apply must preserve staged media.'
|
||||
$script:officeProcesses=@([pscustomobject]@{Name='setup.exe'})
|
||||
$c=Test-StageCleanup
|
||||
Assert-Cleanup ($c.Stats.OfficeStaging.Status -eq 'Skipped' -and $c.Stats.OfficeStaging.EstimateStatus -eq 'Not assessed') 'An installer without a workspace path must block staging cleanup.'
|
||||
$script:officeProcesses=@([pscustomobject]@{Name='worker.exe'; ExecutablePath=(Join-Path $folder 'ODT\worker.exe')})
|
||||
$c=Test-StageCleanup
|
||||
Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count -and $c.Stats.OfficeStaging.Notes -match 'retained') 'A running process must retain its workspace while allowing other abandoned media.'
|
||||
$script:officeProcesses=@(); $script:officeInventoryFails=$true
|
||||
$c=Test-StageCleanup -ReportOnly $false
|
||||
Assert-Cleanup ($c.Errors -eq 1 -and (Test-Path -LiteralPath (Join-Path $folder 'ODT\payload.dat'))) 'Failed process inventory must prevent deletion.'
|
||||
$script:officeInventoryFails=$false
|
||||
& {
|
||||
function New-SystemCleanupOfficeMutex {
|
||||
$m=[pscustomobject]@{}
|
||||
$m | Add-Member ScriptMethod WaitOne { param($Timeout) return $false }
|
||||
$m | Add-Member ScriptMethod Dispose { }
|
||||
return $m
|
||||
}
|
||||
$c=Test-StageCleanup -ReportOnly $false
|
||||
Assert-Cleanup ($c.Stats.OfficeStaging.Status -eq 'Skipped' -and (Test-Path -LiteralPath (Join-Path $folder 'odt.exe'))) 'Active deployment mutex must block cleanup.'
|
||||
}
|
||||
$payload=Join-Path $folder 'ODT\payload.dat'
|
||||
$handle=[IO.File]::Open($payload,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::None)
|
||||
try { $c=Test-StageCleanup; Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count) 'Locked media must not count as reclaimable.' } finally { $handle.Dispose() }
|
||||
[IO.File]::SetLastWriteTimeUtc($payload,[datetime]::UtcNow)
|
||||
$c=Test-StageCleanup
|
||||
Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count) 'A fresh payload must retain the whole workspace media set.'
|
||||
[IO.File]::SetLastWriteTimeUtc($payload,[datetime]::UtcNow.AddDays(-60))
|
||||
$outside=New-CleanupFixture 'office-outside\keep.dat'
|
||||
$junction=Join-Path $folder 'ODT\linked'
|
||||
$null=New-Item -ItemType Junction -Path $junction -Target (Split-Path -Parent $outside)
|
||||
try {
|
||||
[IO.Directory]::SetLastWriteTimeUtc((Split-Path -Parent $junction),[datetime]::UtcNow.AddDays(-60))
|
||||
$c=Test-StageCleanup
|
||||
Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count -and (Test-Path -LiteralPath $outside)) 'Linked artifacts must retain the whole media set without traversing the link.'
|
||||
} finally { [IO.Directory]::Delete($junction,$false); [IO.Directory]::SetLastWriteTimeUtc((Split-Path -Parent $junction),[datetime]::UtcNow.AddDays(-60)) }
|
||||
$marker=Join-Path $folder 'options.json'; [IO.File]::WriteAllText($marker,'{}'); [IO.File]::SetLastWriteTimeUtc($marker,[datetime]::UtcNow.AddDays(-60))
|
||||
$c=Test-StageCleanup
|
||||
Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count) 'Unrecognized folders must not be deleted based only on their names.'
|
||||
[IO.File]::WriteAllText($marker,'{"ProductId":"O365BusinessRetail","OfficeArchitecture":"64","UpdateChannel":"Current"}'); [IO.File]::SetLastWriteTimeUtc($marker,[datetime]::UtcNow.AddDays(-60))
|
||||
$c=Test-StageCleanup -ReportOnly $false
|
||||
Assert-Cleanup ($c.Errors -eq 0 -and $c.Stats.OfficeStaging.RemovedFiles -eq (2*$names.Count) -and !(Test-Path -LiteralPath (Join-Path $folder 'ODT')) -and !(Test-Path -LiteralPath (Join-Path $legacy 'ODT'))) 'Apply must remove known aged media from SystemTemp and legacy ProgramData.'
|
||||
foreach ($workspace in @($folder,$legacy)) {
|
||||
foreach ($name in @('options.json','Office-UserCleanup.ps1','user-cleanup.lock','install.xml','office-install.stdout.log','unknown.exe')) {
|
||||
Assert-Cleanup (Test-Path -LiteralPath (Join-Path $workspace $name)) "Office staging cleanup removed protected data: $name"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# File ages, literal brackets, nested fresh files, no changes in preview.
|
||||
$root=Join-Path $testRoot 'temps'
|
||||
$old=New-CleanupFixture 'temps\old[1].tmp'
|
||||
@@ -558,6 +650,7 @@ try {
|
||||
}
|
||||
}
|
||||
function Test-SystemCleanupAppRunning { return $false }
|
||||
function Get-SystemCleanupOfficeStagingRoots { return (Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment') }
|
||||
function Get-Service { [pscustomobject]@{Status='Stopped'} }
|
||||
function Remove-Item { throw 'PREVIEW MUTATION: Remove-Item' }
|
||||
function New-ItemProperty { throw 'PREVIEW MUTATION: registry write' }
|
||||
@@ -569,13 +662,13 @@ try {
|
||||
$o=Get-SystemCleanupOptions
|
||||
$script:messages=@(); $script:details=@()
|
||||
$result=@(Invoke-SystemCleanup $o)
|
||||
Assert-Cleanup ($result.Count -eq 22 -and @($result | Where-Object Status -ne 'Preview').Count -eq 0) "Full preview did not cover every category (count=$($result.Count))."
|
||||
Assert-Cleanup ($result.Count -eq 23 -and @($result | Where-Object Status -ne 'Preview').Count -eq 0) "Full preview did not cover every category (count=$($result.Count))."
|
||||
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'DownloadedExecutables' -and -not $_.Enabled -and $_.CandidateFiles -eq 1 }).Count -eq 1) 'Default-disabled downloads were not assessed by the entry point.'
|
||||
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'ComponentStore' -and -not $_.Enabled -and $null -eq $_.CandidateBytes -and $_.EstimateStatus -eq 'Not estimated' }).Count -eq 1) 'Unknown native savings must not be reported as zero.'
|
||||
Assert-Cleanup (Test-Path -LiteralPath (Join-Path $env:SystemRoot 'Temp\old.tmp')) 'Full preview removed a fixture.'
|
||||
$compactOutput = ($script:messages | ForEach-Object { '[SystemCleanup] ' + $_ }) -join "`r`n"
|
||||
$script:compactReportBytes = [Text.Encoding]::UTF8.GetByteCount($compactOutput)
|
||||
Assert-Cleanup ($script:compactReportBytes -lt 4096) "22-category preview exceeded the 4 KiB regression budget ($script:compactReportBytes bytes)."
|
||||
Assert-Cleanup ($script:compactReportBytes -lt 4096) "23-category preview exceeded the 4 KiB regression budget ($script:compactReportBytes bytes)."
|
||||
foreach ($row in $result) {
|
||||
Assert-Cleanup ([regex]::Matches($compactOutput, ('(?m)^\[SystemCleanup\] ' + [regex]::Escape($row.Category) + '\s')).Count -eq 1) "Compact report lost or repeated category $($row.Category)."
|
||||
}
|
||||
@@ -604,7 +697,7 @@ try {
|
||||
Assert-Cleanup ($c.Errors -eq 1 -and $report -match 'CrashDumps.*Failed; incomplete.*Synthetic failure.*see verbose' -and $report.Length -lt 1600) 'A long multiline error must retain its failure status without flooding the summary.'
|
||||
Assert-Cleanup (($script:details -join "`n").Contains(('long diagnostic ' * 300))) 'Compacted errors must remain complete in verbose diagnostics.'
|
||||
}
|
||||
Write-Host "Compact 22-category preview: $script:compactReportBytes UTF-8 bytes."
|
||||
Write-Host "Compact 23-category preview: $script:compactReportBytes UTF-8 bytes."
|
||||
Write-Host "PASS: $script:assertions offline cleanup assertions ($($PSVersionTable.PSVersion))."
|
||||
} finally {
|
||||
# Only this test's generated directory; links are removed non-recursively above.
|
||||
|
||||
Reference in New Issue
Block a user