Compare commits

..
2 Commits
Author SHA1 Message Date
dyoder e6604564a7 Merge branch 'master' of https://dev.emberkom.com/emberkom/management-scripts 2026-10-21 12:33:21 -04:00
dyoder 136c88fedf added a few fixes 2026-10-21 09:30:15 -04:00
6 changed files with 607 additions and 33 deletions
+228
View File
@@ -0,0 +1,228 @@
#Requires -Version 5.1
#Requires -RunAsAdministrator
<#
.SYNOPSIS
Lists saved network drive mappings for every local user profile.
.DESCRIPTION
Run in an elevated PowerShell window on the computer being inventoried.
Reads the Network key in each non-system user's registry hive. For unloaded
profiles, temporarily loads NTUSER.DAT (or NTUSER.MAN) under a unique HKU key
and unloads it in a finally block. Does not edit drive mappings or credentials.
Also enumerates mappings visible to this PowerShell logon session, unless
-SavedOnly is specified. These are NOT all other users' live mappings.
Saved mappings may be disconnected or obsolete. No shares are probed.
Temporary mappings in other sessions and unavailable profile containers
cannot be inventoried by this script. Accounts without local profiles are
not included. Warnings identify profiles that could not be fully scanned.
The script returns objects; use Format-Table for display or Export-Csv to save.
Use -Verbose to see the scan result for each profile, including empty profiles.
.EXAMPLE
$drives = .\Get-AllNetworkDrives.ps1 -Verbose
$drives | Format-Table User, Drive, RemotePath, Source -AutoSize -Wrap
.EXAMPLE
.\Get-AllNetworkDrives.ps1 | Export-Csv .\NetworkDrives.csv -NoTypeInformation -Encoding UTF8
#>
[CmdletBinding()]
param(
[switch]$SavedOnly
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
# Capture reg.exe failures without parsing localized success/error messages.
function Invoke-HiveCommand {
param(
[ValidateSet('load', 'unload')][string]$Action,
[string]$MountName,
[string]$HiveFile
)
$ErrorActionPreference = 'Continue'
$PSNativeCommandUseErrorActionPreference = $false
$regExe = Join-Path $env:SystemRoot 'System32\reg.exe'
$messages = if ($Action -eq 'load') {
& $regExe load "HKU\$MountName" $HiveFile 2>&1
} else {
& $regExe unload "HKU\$MountName" 2>&1
}
$exitCode = $LASTEXITCODE
[pscustomobject]@{
ExitCode = $exitCode
Message = ($messages | Out-String).Trim()
}
}
$results = [System.Collections.Generic.List[object]]::new()
$profiles = @(Get-CimInstance -ClassName Win32_UserProfile -ErrorAction Stop |
Where-Object { -not $_.Special -and $_.SID } |
Sort-Object LocalPath)
if ($profiles.Count -eq 0) {
Write-Warning 'Windows reported no non-system user profiles.'
}
$usersKey = [Microsoft.Win32.RegistryKey]::OpenBaseKey(
[Microsoft.Win32.RegistryHive]::Users,
[Microsoft.Win32.RegistryView]::Default
)
try {
foreach ($profile in $profiles) {
$sid = [string]$profile.SID
$userName = $sid
try {
$userName = ([System.Security.Principal.SecurityIdentifier]::new($sid)).Translate(
[System.Security.Principal.NTAccount]
).Value
} catch {
# Keep the SID when a deleted account or offline domain cannot resolve.
Write-Verbose "Account name unavailable for $sid; retaining its SID."
}
$profileKey = $null
$networkKey = $null
$mountedByScript = $false
$mountName = 'DriveInventory_' + [guid]::NewGuid().ToString('N')
$countBefore = $results.Count
try {
# Check the registry itself: the profile's Loaded flag can be stale.
$profileKey = $usersKey.OpenSubKey($sid, $false)
if ($null -eq $profileKey) {
if ([string]::IsNullOrWhiteSpace($profile.LocalPath)) {
throw 'The profile has no local path and its hive is not loaded.'
}
$hiveFile = Join-Path $profile.LocalPath 'NTUSER.DAT'
if (-not (Test-Path -LiteralPath $hiveFile -PathType Leaf)) {
$hiveFile = Join-Path $profile.LocalPath 'NTUSER.MAN'
}
if (-not (Test-Path -LiteralPath $hiveFile -PathType Leaf)) {
throw "Neither NTUSER.DAT nor NTUSER.MAN is available in $($profile.LocalPath)."
}
$loadResult = Invoke-HiveCommand -Action load -MountName $mountName -HiveFile $hiveFile
if ($loadResult.ExitCode -eq 0) {
$mountedByScript = $true
$profileKey = $usersKey.OpenSubKey($mountName, $false)
} else {
# The user may have signed in between our check and reg load.
$profileKey = $usersKey.OpenSubKey($sid, $false)
if ($null -eq $profileKey) {
throw "Could not load the profile hive: $($loadResult.Message)"
}
}
if ($null -eq $profileKey) {
throw 'The profile hive could not be opened after loading.'
}
}
$networkKey = $profileKey.OpenSubKey('Network', $false)
if ($null -ne $networkKey) {
foreach ($letter in $networkKey.GetSubKeyNames()) {
if ($letter -notmatch '^[A-Za-z]$') { continue }
$driveKey = $null
try {
$driveKey = $networkKey.OpenSubKey($letter, $false)
if ($null -eq $driveKey) {
throw "Drive key $letter disappeared during the scan."
}
$remotePath = [string]$driveKey.GetValue('RemotePath', '')
if ([string]::IsNullOrWhiteSpace($remotePath)) {
Write-Warning "${userName}: saved drive ${letter}: has no RemotePath."
continue
}
$results.Add([pscustomobject][ordered]@{
User = $userName
Drive = $letter.ToUpperInvariant() + ':'
RemotePath = $remotePath
Source = 'Saved'
ComputerName = $env:COMPUTERNAME
SID = $sid
ProfilePath = $profile.LocalPath
})
} finally {
if ($null -ne $driveKey) { $driveKey.Dispose() }
}
}
}
Write-Verbose ("{0}: {1} saved mapping(s) found." -f $userName, ($results.Count - $countBefore))
} catch {
Write-Warning "Incomplete scan for $userName [$sid], profile '$($profile.LocalPath)': $($_.Exception.Message)"
} finally {
# Close every child handle BEFORE unloading. Never unload an existing user hive.
if ($null -ne $networkKey) { $networkKey.Dispose() }
if ($null -ne $profileKey) { $profileKey.Dispose() }
if ($mountedByScript) {
$unloadResult = Invoke-HiveCommand -Action unload -MountName $mountName
if ($unloadResult.ExitCode -ne 0) {
Write-Warning "Could not unload HKU\$mountName. $($unloadResult.Message) After closing any handles, run: reg.exe unload HKU\$mountName"
}
}
}
}
} finally {
$usersKey.Dispose()
}
# Supplement saved mappings with those visible to THIS process's logon session.
# This can include temporary mappings, but only for the session running the script.
if (-not $SavedOnly) {
$identity = $null
$network = $null
$sessionDrives = $null
try {
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$currentSid = $identity.User.Value
$network = New-Object -ComObject WScript.Network
$sessionDrives = $network.EnumNetworkDrives()
# WshCollection exposes Count as a COM method, not a PowerShell property.
for ($i = 0; $i -lt $sessionDrives.Count(); $i += 2) {
$drive = [string]$sessionDrives.Item($i)
$remotePath = [string]$sessionDrives.Item($i + 1)
if ($drive -notmatch '^[A-Za-z]:$') { continue }
$matchesSaved = @($results | Where-Object {
$_.SID -eq $currentSid -and $_.Drive -eq $drive -and $_.RemotePath -eq $remotePath
})
if ($matchesSaved.Count -gt 0) {
foreach ($match in $matchesSaved) { $match.Source = 'Saved + CurrentSession' }
} else {
$results.Add([pscustomobject][ordered]@{
User = $identity.Name
Drive = $drive.ToUpperInvariant()
RemotePath = $remotePath
Source = 'CurrentSession'
ComputerName = $env:COMPUTERNAME
SID = $currentSid
ProfilePath = $env:USERPROFILE
})
}
}
} catch {
Write-Warning "Could not fully enumerate current-session drives: $($_.Exception.Message)"
} finally {
if ($null -ne $sessionDrives) {
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($sessionDrives)
}
if ($null -ne $network) {
[void][System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($network)
}
if ($null -ne $identity) { $identity.Dispose() }
}
}
if ($results.Count -eq 0) {
Write-Warning 'No mappings were found in the sources successfully scanned. Review any earlier warnings; other sessions may still have temporary mappings.'
}
$results | Sort-Object User, Drive, RemotePath
+233 -15
View File
@@ -72,6 +72,7 @@ function Get-OfficeDeploymentDefinitions {
AppxRemovalAttempts = 3
UserCleanupWaitMinutes = 20
UserCleanupTaskMinutes = 30
MediaCacheDays = 7
}
}
@@ -139,8 +140,12 @@ function Assert-OfficeCompanionPlatform {
}
function New-OfficeWorkspace {
param(
[string]$Root = (Join-Path ([IO.Path]::GetTempPath()) 'EmberkomOfficeDeployment'),
[ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId = ([guid]::NewGuid().ToString('N'))
)
# Executable content must never be writable by a standard user.
$root = Join-Path $env:ProgramData 'EmberkomOfficeDeployment'
# Default to the execution account's temp location (SYSTEM under Syncro).
$null = New-Item -ItemType Directory -Path $root -Force -ErrorAction Stop
for ($item = Get-Item -LiteralPath $root -Force; $null -ne $item; $item = $item.Parent) {
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Deployment path traverses a reparse point: $($item.FullName)" }
@@ -154,12 +159,198 @@ function New-OfficeWorkspace {
}
$acl.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')))
Set-Acl -LiteralPath $root -AclObject $acl -ErrorAction Stop
$path = Join-Path $root ([guid]::NewGuid().ToString('N'))
$path = Join-Path $root $DeploymentId
$null = New-Item -ItemType Directory -Path $path -ErrorAction Stop
$null = New-Item -ItemType File -Path (Join-Path $path 'user-cleanup.lock') -ErrorAction Stop
$path
}
function New-OfficeUserWorkspace {
param($Media, [string]$Workspace)
# Only deferred user cleanup must survive routine temp purges. SYSTEM's temp
# directory may also be inaccessible to the limited users who run this helper.
$path = New-OfficeWorkspace -Root (Join-Path $env:ProgramData 'EmberkomOfficeDeployment') -DeploymentId (Split-Path -Leaf $Workspace)
$helper = Join-Path $path 'Office-UserCleanup.ps1'
Copy-Item -LiteralPath $Media.Helper -Destination $helper -ErrorAction Stop
$Media.Helper = $helper
$path
}
function Assert-OfficeManagedPath {
param([string]$Root, [string]$Path)
$base = [IO.Path]::GetFullPath($Root).TrimEnd('\')
$target = [IO.Path]::GetFullPath($Path)
if (!$target.StartsWith($base + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "Path is outside the Office deployment root: $target" }
# Check ancestors before enumeration; never follow a junction during deletion or reuse.
for ($cursor = $target; $cursor; $cursor = Split-Path -Parent $cursor) {
if (Test-Path -LiteralPath $cursor) {
if ((Get-Item -LiteralPath $cursor -Force -ErrorAction Stop).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Deployment path traverses a reparse point: $cursor" }
}
}
}
function Get-OfficeManagedFiles {
param([string]$Root, [string]$Path)
Assert-OfficeManagedPath $Root $Path
if (!(Test-Path -LiteralPath $Path)) { return }
$item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
if (!$item.PSIsContainer) { return $item }
foreach ($child in @(Get-ChildItem -LiteralPath $Path -Force -ErrorAction Stop)) {
# Recurse ourselves so a nested junction is rejected BEFORE visiting its target.
Get-OfficeManagedFiles $Root $child.FullName
}
}
function Remove-OfficeManagedItem {
param([string]$Root, [string]$Path)
Assert-OfficeManagedPath $Root $Path
if (!(Test-Path -LiteralPath $Path)) { return }
$null = @(Get-OfficeManagedFiles $Root $Path)
$null = Write-Output "Removing deployment artifact: $Path"
Remove-Item -LiteralPath ([IO.Path]::GetFullPath($Path)) -Recurse -Force -ErrorAction Stop
}
function Get-OfficeStagingNames {
# Only our downloaded artifacts; never Office's installed files or servicing caches.
@('ODT', 'odt.exe', 'odt-download-page.html', 'GetHelp', 'GetHelp.zip', 'media-cache.json')
foreach ($installer in (Get-OfficeDeploymentDefinitions).CompanionInstallers.Values) { $installer.File }
}
function Remove-OfficeStagingFiles {
param([string]$Root, [string]$Workspace)
Assert-OfficeManagedPath $Root $Workspace
foreach ($name in (Get-OfficeStagingNames)) { Remove-OfficeManagedItem $Root (Join-Path $Workspace $name) }
}
function Complete-OfficeDeploymentFiles {
param([string]$Workspace, [string]$UserWorkspace, [string]$PreviousRoot)
$warnings = @()
# This runs only after installation succeeds. No scheduled housekeeping is created.
# Include older temp attempts, but never files still referenced by another process.
$root = Split-Path -Parent $Workspace
$processes = @(Get-CimInstance Win32_Process -ErrorAction Stop)
foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' })) {
try {
Assert-OfficeManagedPath $root $folder.FullName
if (!(Test-Path -LiteralPath (Join-Path $folder.FullName 'options.json'))) { continue }
if (@($processes | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($folder.FullName, [StringComparison]::OrdinalIgnoreCase) -ge 0 }).Count) {
$warnings += "$($folder.FullName) is still in use."
continue
}
Remove-OfficeManagedItem $root $folder.FullName
} catch {
$warnings += "$($folder.FullName): $($_.Exception.Message)"
Write-Error "Could not remove temporary deployment files: $($warnings[-1])" -ErrorAction Continue
}
}
# Earlier versions put downloads in ProgramData. Remove only their known staging
# artifacts after success; old user tasks may still need their helper/lock files.
if ($PreviousRoot -and $PreviousRoot -ne $root -and (Test-Path -LiteralPath $PreviousRoot)) {
foreach ($folder in @(Get-ChildItem -LiteralPath $PreviousRoot -Directory -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' })) {
try {
Assert-OfficeManagedPath $PreviousRoot $folder.FullName
if (!(Test-Path -LiteralPath (Join-Path $folder.FullName 'options.json'))) { continue }
if (@($processes | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($folder.FullName, [StringComparison]::OrdinalIgnoreCase) -ge 0 }).Count) { continue }
Remove-OfficeStagingFiles $PreviousRoot $folder.FullName
} catch {
$warnings += "$($folder.FullName): $($_.Exception.Message)"
Write-Error "Could not remove older deployment downloads: $($warnings[-1])" -ErrorAction Continue
}
}
}
if ($UserWorkspace -and $UserWorkspace -ne $Workspace) {
try {
# Start-OfficeUserCleanup already unregisters completed tasks. Preserve the
# helper whenever any task remains, including a failed unregister attempt.
$id = Split-Path -Leaf $UserWorkspace
$tasks = @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -like "Emberkom-OfficeCleanup-$id-*" })
if (!$tasks.Count) { Remove-OfficeManagedItem (Split-Path -Parent $UserWorkspace) $UserWorkspace }
} catch {
$warnings += "$UserWorkspace : $($_.Exception.Message)"
Write-Error "Could not remove completed user cleanup files: $($warnings[-1])" -ErrorAction Continue
}
}
return ,$warnings
}
function Get-OfficeMediaCacheKey {
param($Options)
$definitions = Get-OfficeDeploymentDefinitions
# Company, activation, app shutdown, and reboot choices affect XML, not the payload.
$contract = [ordered]@{
Schema=1; Product=$Options.ProductId; Architecture=$Options.OfficeArchitecture
Channel=$Options.UpdateChannel; Language=$definitions.Language
OdtPage=$definitions.OdtPage; ExcludedApps=$definitions.OdtExcludedApps
Downloads=@(Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams | ForEach-Object { "$($_.Name)|$($_.File)|$($_.Uri)" })
}
$sha = [Security.Cryptography.SHA256]::Create()
try { ([BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes(($contract | ConvertTo-Json -Depth 5 -Compress))))).Replace('-', '') }
finally { $sha.Dispose() }
}
function Save-OfficeMediaCache {
param($Options, $Media, [string]$Workspace, [string]$CreatedUtc = ([DateTime]::UtcNow.ToString('o')))
$root = Split-Path -Parent $Workspace
$files = @()
foreach ($name in @('ODT', 'odt.exe') + @(Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams | ForEach-Object { $_.File })) {
foreach ($file in @(Get-OfficeManagedFiles $root (Join-Path $Workspace $name))) {
$files += [pscustomobject]@{ Path=$file.FullName.Substring($Workspace.TrimEnd('\').Length + 1); Length=$file.Length; Hash=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256 -ErrorAction Stop).Hash }
}
}
[ordered]@{ Schema=1; Key=(Get-OfficeMediaCacheKey $Options); CreatedUtc=$CreatedUtc; Version=$Media.Version; Files=$files } |
ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $Workspace 'media-cache.json') -Encoding UTF8 -ErrorAction Stop
}
function Restore-OfficeMediaCache {
param($Options, [string]$Workspace)
$root = Split-Path -Parent $Workspace
$definitions = Get-OfficeDeploymentDefinitions
$key = Get-OfficeMediaCacheKey $Options
foreach ($candidate in @(Get-ChildItem -LiteralPath $root -Directory -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' -and $_.FullName -ne $Workspace } | Sort-Object LastWriteTimeUtc -Descending)) {
$manifestPath = Join-Path $candidate.FullName 'media-cache.json'
if (!(Test-Path -LiteralPath $manifestPath)) { continue }
$inUse = @(Get-CimInstance Win32_Process -ErrorAction Stop | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($candidate.FullName, [StringComparison]::OrdinalIgnoreCase) -ge 0 })
if ($inUse.Count) { throw "A previous Office deployment still has active processes using $($candidate.FullName). Wait for them to finish before retrying." }
try {
Assert-OfficeManagedPath $root $manifestPath
$manifest = Get-Content -LiteralPath $manifestPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
$created = [DateTime]::Parse($manifest.CreatedUtc).ToUniversalTime()
if ($manifest.Schema -ne 1 -or $manifest.Key -ne $key -or $created -gt [DateTime]::UtcNow -or $created -lt [DateTime]::UtcNow.AddDays(-$definitions.MediaCacheDays)) { continue }
if ($manifest.Version -notmatch $definitions.OfficeBuildPattern -or !$manifest.Files.Count) { throw 'Invalid cache manifest.' }
$names = @('ODT', 'odt.exe') + @(Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams | ForEach-Object { $_.File })
foreach ($entry in $manifest.Files) {
if ([IO.Path]::IsPathRooted($entry.Path) -or $entry.Path -match '(^|[\\/])\.\.([\\/]|$)' -or ($entry.Path -split '[\\/]')[0] -notin $names) { throw 'Invalid cached file path.' }
$path = Join-Path $candidate.FullName $entry.Path
Assert-OfficeManagedPath $candidate.FullName $path
$file = Get-Item -LiteralPath $path -ErrorAction Stop
if ($file.Length -ne $entry.Length -or (Get-FileHash -LiteralPath $path -Algorithm SHA256 -ErrorAction Stop).Hash -ne $entry.Hash) { throw "Cached file changed: $path" }
}
# Verify every executable we will launch, in addition to the cached hashes.
foreach ($name in @('odt.exe', 'ODT\setup.exe') + @(Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams | ForEach-Object { $_.File })) {
Assert-OfficeMicrosoftSignature (Join-Path $candidate.FullName $name)
}
$actualFiles = @(foreach ($name in $names) { Get-OfficeManagedFiles $root (Join-Path $candidate.FullName $name) })
$actualPaths = @($actualFiles | ForEach-Object { $_.FullName.Substring($candidate.FullName.Length + 1) } | Sort-Object -Unique)
$expectedPaths = @($manifest.Files.Path | Sort-Object -Unique)
if ($actualFiles.Count -ne $manifest.Files.Count -or (Compare-Object $actualPaths $expectedPaths)) { throw 'Cached file inventory changed.' }
} catch {
$null = Write-Output "Ignoring unusable Office cache in $($candidate.FullName): $($_.Exception.Message)"
continue
}
# Transfer rather than duplicate several GB. Each deployment still has a new ID,
# so old per-user completion markers cannot suppress a new cleanup request.
foreach ($name in $names) {
$source = Join-Path $candidate.FullName $name; $destination = Join-Path $Workspace $name
Assert-OfficeManagedPath $root $source; Assert-OfficeManagedPath $root $destination
if (Test-Path -LiteralPath $destination) { throw "Cache destination already exists: $destination" }
Move-Item -LiteralPath $source -Destination $destination -ErrorAction Stop
}
Remove-OfficeManagedItem $root $manifestPath
$null = Write-Output "Reusing verified Office $($manifest.Version) media from $($candidate.FullName)."
return $manifest
}
}
function Assert-OfficeMicrosoftSignature {
param([string]$Path)
$signature = Get-AuthenticodeSignature -LiteralPath $Path -ErrorAction Stop
@@ -276,6 +467,24 @@ function Initialize-OfficeMedia {
param($Options, [string]$Workspace)
$definitions = Get-OfficeDeploymentDefinitions
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Always refresh the small helper from this repository, even when using cached media.
$helper = Join-Path $Workspace 'Office-UserCleanup.ps1'
Save-OfficeDownload "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1" $helper
$tokens = $null; $errors = $null
$null = [Management.Automation.Language.Parser]::ParseFile($helper, [ref]$tokens, [ref]$errors)
if ($errors.Count -or !(Select-String -LiteralPath $helper -SimpleMatch $definitions.HelperVersion -Quiet)) { throw 'Office user cleanup helper is invalid; publish it with this installer.' }
$cached = Restore-OfficeMediaCache $Options $Workspace
if ($cached) {
$odtFolder = Join-Path $Workspace 'ODT'
$configPath = Join-Path $Workspace 'install.xml'; $removalPath = Join-Path $Workspace 'remove.xml'
$config = New-OfficeConfiguration $Options $odtFolder $cached.Version; $config.Save($configPath)
$removal = New-OfficeRemovalConfiguration $Options; $removal.Save($removalPath)
$companions = @{}
foreach ($download in (Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams)) { $companions[$download.Name] = Join-Path $Workspace $download.File }
# Preserve the original expiry; repeated validation must not keep old media forever.
$cached | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $Workspace 'media-cache.json') -Encoding UTF8 -ErrorAction Stop
return [pscustomobject]@{ Setup=(Join-Path $odtFolder 'setup.exe'); RemovalConfig=$removalPath; Config=$configPath; Helper=$helper; Version=$cached.Version; Companions=$companions; CachedMediaReused=$true }
}
$pagePath = Join-Path $Workspace 'odt-download-page.html'
Save-OfficeDownload $definitions.OdtPage $pagePath -TimeoutSeconds $definitions.OdtPageTimeoutSeconds
$url = Get-OfficeOdtDownloadUrl (Get-Content -LiteralPath $pagePath -Raw -ErrorAction Stop)
@@ -289,12 +498,6 @@ function Initialize-OfficeMedia {
$setup = Join-Path $odtFolder 'setup.exe'; Assert-OfficeMicrosoftSignature $setup
$removalPath = Join-Path $Workspace 'remove.xml'
$removal = New-OfficeRemovalConfiguration $Options; $removal.Save($removalPath)
# Run-Script only downloads the core file, so stage its helper explicitly.
$helper = Join-Path $Workspace 'Office-UserCleanup.ps1'
Save-OfficeDownload "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1" $helper
$tokens = $null; $errors = $null
$null = [Management.Automation.Language.Parser]::ParseFile($helper, [ref]$tokens, [ref]$errors)
if ($errors.Count -or !(Select-String -LiteralPath $helper -SimpleMatch $definitions.HelperVersion -Quiet)) { throw 'Office user cleanup helper is invalid; publish it with this installer.' }
$configPath = Join-Path $Workspace 'install.xml'
$config = New-OfficeConfiguration $Options $odtFolder; $config.Save($configPath)
$null = Write-Output 'Downloading Office installation files before removing installed apps.'
@@ -314,7 +517,9 @@ function Initialize-OfficeMedia {
}
$config.Configuration.Add.SetAttribute('Version', $versions[0].Name); $config.Save($configPath)
$companions = Initialize-OfficeCompanionMedia $Workspace -InstallTeams $Options.InstallTeams
[pscustomobject]@{ Setup = $setup; RemovalConfig = $removalPath; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions }
$media = [pscustomobject]@{ Setup = $setup; RemovalConfig = $removalPath; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions; CachedMediaReused=$false }
Save-OfficeMediaCache $Options $media $Workspace
$media
}
function Get-OfficeRunningApps {
@@ -746,6 +951,7 @@ function Invoke-OfficeDeployment {
$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
$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) {
@@ -754,13 +960,16 @@ function Invoke-OfficeDeployment {
$media = Initialize-OfficeMedia $Options $workspace
if ($Options.ValidateBeforeChanges) {
$existingOffice = @(Get-OfficeSuiteInventory | ForEach-Object { $_.DisplayName })
$null = Write-Output 'Validation passed. Stopped before closing apps, uninstalling, clearing identities, registering tasks, or installing.'
# This helper is refreshed on every run; validation does not need to retain it.
Remove-OfficeManagedItem $root $media.Helper
$null = Write-Output 'Validation passed. Stopped before closing apps, uninstalling, clearing identities, registering user cleanup tasks, or installing.'
return [pscustomobject]@{
OfficeDeploymentStatus='ValidationPassed'; ExitCode=0; ValidateBeforeChanges=$true
ProductId=$Options.ProductId; OfficeVersion=$media.Version; Architecture=$Options.OfficeArchitecture
UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams; OfficeRemovalMethod='SilentODT'; DeferReboot=$Options.DeferReboot
Workspace=$workspace; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps
NextStep='Set ValidateBeforeChanges=false to deploy. That run repeats validation and downloads fresh media.'
CachedMediaReused=[bool]$media.CachedMediaReused; MediaCacheDays=(Get-OfficeDeploymentDefinitions).MediaCacheDays
NextStep='Set ValidateBeforeChanges=false to deploy. Matching unexpired media is verified and reused; prerequisites are checked again.'
}
}
Stop-OfficeDeploymentApps $Options
@@ -775,8 +984,10 @@ function Invoke-OfficeDeployment {
return [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @() }
}
foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile }
$pending = Start-OfficeUserCleanup $profiles $media $workspace
Set-OfficeReinstallPhase $workspace
$userWorkspace = $workspace
if ($profiles.Count) { $userWorkspace = New-OfficeUserWorkspace $media $workspace }
$pending = Start-OfficeUserCleanup $profiles $media $userWorkspace
Set-OfficeReinstallPhase $userWorkspace
$code = Install-OfficeMedia $Options $media $workspace
$companions = Install-OfficeCompanionApps $media.Companions $workspace -InstallTeams $Options.InstallTeams
if ($reboot -or $removalCode -eq 3010 -or $companions.ExitCode -eq 3010) { $code = 3010 }
@@ -785,7 +996,13 @@ 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.'
[pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if ($pending.Count -and $code -eq 0) { 2 } else { $code }); RestartRequired=($code -eq 3010); DeferReboot=$Options.DeferReboot; ValidateBeforeChanges=$false; Workspace = $workspace; PendingUserSids = $pending; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version }
$cleanupWarnings = @()
try {
$cleanupWarnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace -PreviousRoot (Join-Path $env:ProgramData 'EmberkomOfficeDeployment')
}
catch { $cleanupWarnings = @($_.Exception.Message); Write-Error "Office deployment file cleanup was incomplete: $($cleanupWarnings[0])" -ErrorAction Continue }
if ($cleanupWarnings.Count) { $null = Write-Output 'Installation succeeded, but some deployment files remain; see the diagnostic log.' }
[pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if ($pending.Count -and $code -eq 0) { 2 } else { $code }); RestartRequired=($code -eq 3010); DeferReboot=$Options.DeferReboot; ValidateBeforeChanges=$false; Workspace = $workspace; UserCleanupWorkspace=$(if ($profiles.Count) { $userWorkspace } else { $null }); PendingUserSids = $pending; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version; CachedMediaReused=[bool]$media.CachedMediaReused; ArtifactCleanupPending=($cleanupWarnings.Count -gt 0) }
} finally {
if ($locked) { $mutex.ReleaseMutex() }
$mutex.Dispose()
@@ -839,7 +1056,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 staging current installers/Office media (several GB). No app shutdown, cleanup, or installation will run.'
Microsoft.PowerShell.Utility\Write-Output 'Validation only: checking prerequisites and verifying cached media or staging current installers (several GB). No app shutdown, Office/user cleanup, or installation will run.'
} else {
Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: validating and staging media, then silently removing Office with ODT and reinstalling Office and the selected companion apps.'
}
@@ -852,6 +1069,7 @@ function Invoke-OfficeDeploymentEntry {
$null = Write-Output $receipt
Microsoft.PowerShell.Utility\Write-Output $receipt
if ($deployment[0].OfficeDeploymentStatus -like 'Installed*') {
if ($deployment[0].ArtifactCleanupPending) { Microsoft.PowerShell.Utility\Write-Output 'WARNING: Installation succeeded, but some deployment files could not be cleaned up. See the diagnostic log; no background cleanup is scheduled.' }
if ($deployment[0].ExitCode -eq 3010) { Microsoft.PowerShell.Utility\Write-Output 'A restart is required to finish deployment; no automatic reboot was requested.' }
Microsoft.PowerShell.Utility\Write-Output 'Users may need to sign out and back in for companion app registration; check PendingUserSids for deferred cleanup.'
}
+15 -11
View File
@@ -19,19 +19,23 @@ End-Process -Name 'Teams' -Match -Force
# URL to the OffscrubC2R.vbs script
$UninstallScriptURL = 'https://github.com/OfficeDev/Office-IT-Pro-Deployment-Scripts/raw/master/Office-ProPlus-Deployment/Deploy-OfficeClickToRun/OffScrubc2r.vbs'
# The path to the local script once downloaded
$UninstallScript = Download-File -URL $UninstallScriptURL
# Use an owned, unique file so partial downloads can also be removed in finally.
$UninstallScript = Join-Path (Get-TempPath) ('OfficeUninstall-' + [guid]::NewGuid().ToString('N') + '.vbs')
# Args to pass to the OffscrubC2R.vbs script
$ScriptArgs = "/ALL /QUIET /NOCANCEL"
# Run the script
Write-Output "Uninstalling all Click2Run versions of Office"
Try { Start-Process "cscript.exe" -ArgumentList "//nologo ""${UninstallScript}"" ${ScriptArgs}" -Wait }
Catch { Write-Error $_.Exception.Message }
# Delete the downloaded script
If ( Test-Path $UninstallScript ) {
Write-Output "Deleting downloaded script: ""${UninstallScript}"""
Remove-Item -Path $UninstallScript -Force -ErrorAction SilentlyContinue
try {
$null = Download-File -URL $UninstallScriptURL -File $UninstallScript
Write-Output 'Uninstalling all Click2Run versions of Office'
Start-Process 'cscript.exe' -ArgumentList "//nologo `"$UninstallScript`" $ScriptArgs" -Wait -WindowStyle Hidden -ErrorAction Stop
} catch {
Write-Error $_.Exception.Message -ErrorAction Continue
throw
} finally {
if (Test-Path -LiteralPath $UninstallScript -PathType Leaf) {
Write-Output "Deleting downloaded script: $UninstallScript"
try { Remove-Item -LiteralPath $UninstallScript -Force -ErrorAction Stop }
catch { Write-Error "Could not delete $UninstallScript : $($_.Exception.Message)" -ErrorAction Continue }
}
}
+20 -5
View File
@@ -60,15 +60,15 @@ 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 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, 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.
Validation writes logs and staging files, secures its workspace, and runs ODT extraction and `/download`; it is not a zero-write inventory scan. Allow several GB and the same download time as deployment. A later `false` run downloads fresh media and repeats the checks. Validation does not prove tenant entitlements, successful future uninstallation/activation, or availability of the online companion payloads at install time.
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 verifying its SHA-256 hashes and Microsoft executable signatures. 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.
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.
ODT downloads the current build in the selected channel first. Installation is pinned to that local build, uses English (`en-us`), enables updates, and uses `Display Level="None"`. 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.
On a cache miss, ODT downloads the current build in the selected channel. A cache hit uses the build validated earlier, for at most seven days from the original download; it does not check for a newer build during that interval. Installation is pinned to that local build, uses English (`en-us`), enables updates, and uses `Display Level="None"`. 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.
The companion apps remain excluded from ODT because the main script installs the selected companions explicitly for all users after Office. Their installers are downloaded from Microsoft's evergreen links and their Microsoft Authenticode signatures checked before any removal; Teams is staged only when the subscription includes it. Teams, new Outlook, and WebView2 use online bootstrappers: only their installer executables are staged, and their payload downloads can still fail later. The complete Office suite payload is staged before removal.
@@ -113,7 +113,20 @@ A file lock serializes user uninstallers with the transition to reinstallation.
Windows work/school registration, WAM/AAD BrokerPlugin, generic Windows credentials, and device enrollment are preserved. This intentionally does not remove every Microsoft sign-in token. Microsoft's [activation reset guide](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365-apps/activation/reset-activation-state) distinguishes Office caches from shared WAM and workplace registration state.
A deployment is reported as **InstalledWithUserCleanupPending** if any user task has not completed. Failed tasks also remain pending and retry on later sign-ins. The helper writes `Status=Complete` under `HKCU\Software\Emberkom\OfficeDeployment\<deployment-id>` after success and then becomes a no-op. Tasks completed during deployment are removed automatically. Tasks that finish later remain registered; an administrator can confirm their marker/task result and unregister those exact tasks afterward. Do not delete their helper while any cleanup is pending.
A deployment is reported as **InstalledWithUserCleanupPending** if any user task has not completed. Failed tasks also remain pending and retry on later sign-ins. The helper writes `Status=Complete` under `HKCU\Software\Emberkom\OfficeDeployment\<deployment-id>` after success and then becomes a no-op. Tasks completed during deployment are removed automatically. Tasks that finish later retain their previous behavior: they remain registered but do no further work after success. An administrator can confirm completion and remove those exact tasks and their helper afterward. There is no daily housekeeping task.
The helper, lock, and reinstall marker for these previously agreed logon tasks live separately in `%ProgramData%\EmberkomOfficeDeployment\<deployment-id>`, so routine temp cleanup cannot break deferred user cleanup. The receipt identifies this folder as `UserCleanupWorkspace`. If no user tasks remain at the end of a successful deployment, the script removes this helper folder too. It is the only deployment code intentionally retained for pending users; the main installer does not persist on the endpoint.
## Temporary media and cleanup during deployment
- A completed staging pass records a protected `media-cache.json` inventory with file hashes, version, original creation time, and a matching key derived from product, architecture, channel, language, 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`.
- 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, modified, unsigned, or incompatible caches are not reused. 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.
## Results and troubleshooting
@@ -130,7 +143,9 @@ 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, generated XML, and downloaded media remain in `%ProgramData%\EmberkomOfficeDeployment\<deployment-id>`. 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 script records this folder in the Tools log and receipt. The separate limited-user cleanup task does not share the elevated Tools execution context; its transcript remains in `%LOCALAPPDATA%\Emberkom\OfficeDeployment\<deployment-id>.log` for each user. Retained media can consume several GB per attempt. A validation-only folder can be removed after reviewing its results; for deployment folders, first remove all associated scheduled tasks. ODT may also write diagnostic logs to the executing account's temp directory.
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.
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.
The installer verifies the selected Office product, bitness, and downloaded version in Click-to-Run registration, plus selected companion deployment as listed above. The final receipt includes `CompanionApps` versions and `TeamsSelected`; when Teams is skipped, it has no installed version in that receipt. Any selected companion installer or verification failure fails the deployment, even if Office installed successfully. It does not claim that the subscription has activated. It does not delete mail profiles, revoke cloud sessions, or roll back a removed Office installation.
+2
View File
@@ -0,0 +1,2 @@
. $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1')))
Run-Script -LivePSScript Get-AllNetworkDrives
+108 -1
View File
@@ -650,6 +650,105 @@ try {
Assert-OfficeTest ($pending.Count -eq 1 -and $pending[0] -eq 'logged-off') 'Completed task housekeeping must not fail deployment or mark completed cleanup pending.'
}
# Real temporary files for cache reuse/tampering; no installer or network may run.
& {
$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-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
$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.'
$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); $changedBytes = $originalBytes.Clone(); $changedBytes[0] = $changedBytes[0] -bxor 1; [IO.File]::WriteAllBytes($stream, $changedBytes)
Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Same-size payload corruption passed hash verification.'
[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
$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 ((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'
}
# Cleanup runs synchronously on success. Downloads are temporary; pending-user
# helpers have a separate durable folder and are never part of the media cache.
& {
$root = Join-Path $testRoot 'temporary-downloads'; $null = [IO.Directory]::CreateDirectory($root)
$workspace = Join-Path $root ('c' * 32); $null = [IO.Directory]::CreateDirectory($workspace)
foreach ($name in @('options.json', 'Office-UserCleanup.ps1', 'user-cleanup.lock', 'office-install.stdout.log', 'odt.exe')) { Set-Content -LiteralPath (Join-Path $workspace $name) -Value 'fixture' }
$null = [IO.Directory]::CreateDirectory((Join-Path $workspace 'ODT'))
Set-Content -LiteralPath (Join-Path $workspace 'ODT\payload') -Value 'fixture'
$userRoot = Join-Path $testRoot 'durable-user-helpers'; $null = [IO.Directory]::CreateDirectory($userRoot)
function New-OfficeWorkspace {
param($Root,$DeploymentId)
Assert-OfficeTest ($Root -eq (Join-Path $env:ProgramData 'EmberkomOfficeDeployment') -and $DeploymentId -eq ('c' * 32)) 'Pending-user helper must use a separate protected ProgramData workspace.'
$path = Join-Path $userRoot $DeploymentId; $null = [IO.Directory]::CreateDirectory($path)
Set-Content -LiteralPath (Join-Path $path 'user-cleanup.lock') -Value ''
$path
}
$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.'
$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'} } }
function Register-ScheduledTask { throw 'File cleanup must not register any task.' }
$warnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace
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.'
$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.'
}
# The legacy uninstaller must delete both successful and partial downloads.
& {
$legacy = Read-OfficeAst 'Uninstall-MicrosoftOffice.ps1'
function End-Process { }
function Get-TempPath { $testRoot }
function Download-File { param($URL,$File) $script:legacyDownload=$File; Set-Content -LiteralPath $File -Value 'inert VBS'; if ($script:legacyMode -eq 'download') { throw 'synthetic download failure' }; $File }
function Start-Process { if ($script:legacyMode -eq 'launch') { throw 'synthetic launch failure' } }
foreach ($script:legacyMode in @('success', 'download', 'launch')) {
$failed=$false
try { $null = & ([scriptblock]::Create($legacy.Extent.Text)) 2>$null } catch { $failed=$true }
Assert-OfficeTest (!(Test-Path -LiteralPath $script:legacyDownload)) "Legacy uninstaller left its $script:legacyMode download behind."
Assert-OfficeTest ($failed -eq ($script:legacyMode -ne 'success')) 'Legacy cleanup swallowed the original failure.'
}
}
# Test orchestration with every machine mutation mocked.
& {
function New-Object {
@@ -659,6 +758,9 @@ try {
throw "Unexpected object requested by orchestration fixture: $TypeName"
}
function Assert-OfficeDeploymentHost { }
function Complete-OfficeDeploymentFiles { param($Workspace,$UserWorkspace,$PreviousRoot) $script:artifactCleanupRuns++; 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 Start-Transcript { }
function Stop-Transcript { }
@@ -668,7 +770,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 { $script:events += 'download'; if ($script:mode -eq 'download') { throw 'download failure' }; [pscustomobject]@{Version='16.0.1.2'} }
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 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' } }
@@ -679,6 +781,7 @@ try {
$script:removalStillRegistered=$false
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'; DeferReboot='false'}
foreach ($script:mode in @('success','download','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 = $_ }
if ($script:mode -in @('success','pending','reboot','office-reboot','companion-reboot')) {
@@ -689,9 +792,13 @@ try {
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.' }
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"
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='cleanup-warning'; $script:events=@()
$result = @(Invoke-OfficeDeployment $options)
Assert-OfficeTest ($result.Count -eq 1 -and $result[0].ArtifactCleanupPending -and $result[0].ExitCode -eq 0 -and $result[0].OfficeDeploymentStatus -eq 'Installed') 'Artifact cleanup problems corrupted the receipt or failed a verified installation.'
foreach ($script:mode in @('reboot','office-reboot')) {
foreach ($script:removalStillRegistered in @($false,$true)) {
$script:events=@()