Compare commits

..
15 Commits
24 changed files with 2701 additions and 462 deletions
+79 -2
View File
@@ -2,6 +2,17 @@
## RMM script execution model ## RMM script execution model
Target **Windows PowerShell 4.0** by default for new Windows RMM scripts. Put
`#Requires -Version 4.0` in both the RMM caller and its downloaded core. Use
4.0-compatible syntax, cmdlets and .NET APIs throughout their execution path,
including shared helpers. If a workload genuinely needs a newer version,
document the dependency alongside its version requirement.
This is the required convention for new RMM scripts. Read both
[`Install-MicrosoftOffice365.ps1`](Install-MicrosoftOffice365.ps1) and its
[`rmm/Install-MicrosoftOffice365.ps1`](rmm/Install-MicrosoftOffice365.ps1) caller
as the reference implementation before designing script inputs or a loader.
Scripts in this repository are generally executed by a small caller script in the RMM. The caller first downloads and dot-sources `Tools.ps1` from the public repository URL: Scripts in this repository are generally executed by a small caller script in the RMM. The caller first downloads and dot-sources `Tools.ps1` from the public repository URL:
```powershell ```powershell
@@ -14,8 +25,74 @@ The caller then invokes `Run-Script`, passing the repository script's filename w
Run-Script -LivePSScript Create-BatteryReport Run-Script -LivePSScript Create-BatteryReport
``` ```
For a live PowerShell script without `-Arguments`, `Run-Script` downloads the target script and dot-sources it. This keeps the core script logic in version control, and changes pushed to the repository take effect in production without updating each RMM caller. The live-script calling convention preserves the caller's PowerShell context so
the downloaded core can read the caller's variables. Dot-sourcing (`. $ScriptFile`
or `. $ScriptBlock`) is the standard way to provide this shared scope. Keep the
core logic in version control so repository updates take effect without replacing
each RMM caller. `Run-Script` has separate execution branches; verify variable
visibility against the actual helper when changing a loader.
When a repository script needs RMM-provided input, define the variable in the RMM caller before calling `Run-Script`. Because the target is dot-sourced into the caller's scope, it can read that variable directly. When a repository script needs RMM-provided input, define the variable in the RMM caller before calling `Run-Script`. The downloaded core reads that variable directly from the inherited scope.
When changing `Run-Script` or scripts invoked through it, preserve this shared-scope behavior unless the change explicitly includes migrating all affected RMM callers. When changing `Run-Script` or scripts invoked through it, preserve this shared-scope behavior unless the change explicitly includes migrating all affected RMM callers.
## RMM inputs are caller variables containing strings
- Define/configure operator inputs in the RMM shim, before loading the core. The
RMM supplies **strings only**, even for boolean, integer, and list settings.
- The core reads inherited variables, as the Office installer does. Do **not**
introduce script-level `param(...)` blocks, command-line flags, or a public
`-Options` hashtable for RMM settings. Helper functions inside a script may
still declare parameters for their internal interfaces.
- Do not pass RMM settings through `Run-Script -Arguments`. Use
`Run-Script -LivePSScript <filename-without-extension>` with caller variables
already defined. Do not add a new PowerShell process/runspace for convenience:
it does not inherit those variables. If a new process is required, explicitly
transfer the inputs, as the Office installer does for its native-host relaunch.
- Never overwrite values injected by the RMM. When defaults are appropriate,
distinguish a missing variable from a supplied blank/false value. A core can
use `Get-Variable -Name ... -ErrorAction SilentlyContinue` to collect optional
inputs without redefining them or relying on a script parameter block.
- Convert boolean strings with **`ConvertTo-RmmBoolean` from `Tools.ps1`**.
Never use `[bool]$Text`: a nonempty string such as `'false'` casts to true.
- Parse semicolon-separated list strings with
**`@(ConvertTo-RmmList -Value $Text)` from `Tools.ps1`**. The helper trims items
and removes empty entries; `@(...)` ensures an array for zero/one/many items.
It does not validate or resolve paths. Validate share names/paths in the core
according to the workload. Keep reusable conversion helpers in `Tools.ps1`;
do not duplicate their implementation in individual scripts.
- Parse integer strings explicitly and validate the allowed range. Keep the
original caller values intact and use separate normalized internal values.
- For a permanent endpoint shim launched later by a backup agent, persist its
configured **string** values in that shim. Variables injected into an earlier
RMM process do not survive into the backup agent's new PowerShell process.
Example values in a caller (the RMM may inject these rather than assigning them
in the script):
```powershell
$QuickBooksShareNames = 'QBData;QBArchive'
$QuickBooksForceClose = 'true'
$QuickBooksGraceSeconds = '60'
```
## Tools loading and verification
- Download `Tools.ps1` live when needed. **Do not cache `Tools.ps1` or its helper
definitions**, or introduce an offline Tools fallback. This is an explicit
repository preference; the cloud-backup workflow requires network access.
- Set TLS 1.2 before the first HTTPS download on Windows PowerShell 4.0 and 5.x.
- Normally dot-source live `Tools.ps1` as shown above, then call `Run-Script`.
The QuickBooks permanent backup shim has a documented specialized loader: it
downloads Tools live and dot-sources only its two conversion definitions to
avoid running unrelated setup/logging during backup. This is not a reason to
replace the standard loader in other scripts. Each QuickBooks shim downloads
its matching root script (Stop or Start), which downloads the shared routines
from `resources/quickbooks/QuickBooksBackup.ps1`. All code is fetched live;
only recovery state/logs persist. Start must not call a local Stop shim or use
a cached Stop script in a hidden restore mode.
- Test shim-to-core input visibility, string conversions, and exit-code
propagation when changing these boundaries. Mock downloads and disruptive
actions. For the 4.0 baseline, run on Windows PowerShell 4.0 when available.
Otherwise check compatibility against the Server 2012 R2 / PowerShell 4.0
profile and run the focused tests on Windows PowerShell 5.1.
+31 -28
View File
@@ -1,30 +1,34 @@
$DNSHelper = $Global:ToolsDirectory + '\ekdns.exe' $DNSHelper = $Global:ToolsDirectory + '\ekdns.exe'
$DNSHelperRequiredVersion = '2.3.0' # SHA-256 of ekdns.exe from each v2.3.0 Windows release archive.
$DownloadRequired = $false If ([Environment]::Is64BitOperatingSystem) {
$DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x64-exe/download/ekdns-x64.exe'
If (Test-Path $DNSHelper) { $DNSHelperHash = '308E36680C0E4AD7CE802F4B1D8C38E89B0D8E24BBCE4F33550721C78BA2224C'
$versionOutput = (& $DNSHelper 2>&1 | Select-Object -First 1)
If ($versionOutput -match 'v(\d+\.\d+\.\d+)') {
If ($Matches[1] -ne $DNSHelperRequiredVersion) {
$DownloadRequired = $true
}
} Else {
$DownloadRequired = $true
}
} Else { } Else {
$DownloadRequired = $true $DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x86-exe/download/ekdns-x86.exe'
$DNSHelperHash = 'F987E75D8FFB87B587B57D2394131B072957C0E3EB6B73B4FB784E9B0D65277B'
} }
# Download the latest version of ekDNSHelper $InstalledHash = (Get-FileHash -LiteralPath $DNSHelper -Algorithm SHA256 -ErrorAction SilentlyContinue).Hash
If ($DownloadRequired) { If ($InstalledHash -ne $DNSHelperHash) {
$DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x64-exe/download/ekdns-x64.exe' $StagedHelper = $DNSHelper + '.' + [guid]::NewGuid().ToString('N') + '.tmp'
If (!(Test-Path ${Env:ProgramFiles(x86)})) { Try {
$DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x86-exe/download/ekdns-x86.exe' Write-Output "Downloading latest version of ekDNSHelper"
$null = Download-File -URL $DNSHelperURL -File $StagedHelper
If ((Get-FileHash -LiteralPath $StagedHelper -Algorithm SHA256 -ErrorAction Stop).Hash -ne $DNSHelperHash) {
Throw 'Downloaded ekdns.exe failed SHA-256 verification.'
}
If ([IO.File]::Exists($DNSHelper)) {
[IO.File]::Replace($StagedHelper, $DNSHelper, [NullString]::Value)
} Else {
[IO.File]::Move($StagedHelper, $DNSHelper)
}
} Catch {
Write-Error $_.Exception.Message
Exit 1
} Finally {
Remove-Item -LiteralPath $StagedHelper -Force -ErrorAction SilentlyContinue
} }
If (Test-Path $DNSHelper) { Remove-Item -Path $DNSHelper -Force -ErrorAction SilentlyContinue }
Write-Output "Downloading latest version of ekDNSHelper"
Download-File -URL $DNSHelperURL -File $DNSHelper
} }
# Delete the old version of ekDNSHelper if it exists # Delete the old version of ekDNSHelper if it exists
@@ -62,15 +66,14 @@ If ( Test-Path $DNSHelper ) {
$commandString = """${DNSHelper}"" add -host ${HostString}" $commandString = """${DNSHelper}"" add -host ${HostString}"
$content = $RefreshScriptHeader + $commandString $content = $RefreshScriptHeader + $commandString
Write-Output "Creating latest refresh script" Write-Output "Creating latest refresh script"
If ( Test-Path $RefreshScript ) { Remove-Item -Path $RefreshScript -Force }
Try { Try {
New-Item -Path $RefreshScript -ItemType File -Force | Out-Null Set-Content -LiteralPath $RefreshScript -Value $content -Force -ErrorAction Stop
Set-Content -Path $RefreshScript -Value $content Write-Output "Updating local hosts file with name-to-IP mappings for the following host(s): ${HostString}"
& "${RefreshScript}"
If ($LASTEXITCODE -ne 0) { Exit $LASTEXITCODE }
} }
Catch { Write-Error $_.Exception.Message } Catch { Write-Error $_.Exception.Message ; Exit 1 }
Write-Output "Updating local hosts file with name-to-IP mappings for the following host(s): ${HostString}"
& "${RefreshScript}"
} Else { } Else {
Write-Error "Cannot find the DNS Helper executable: ""${DNSHelper}""" Write-Error "Cannot find the DNS Helper executable: ""${DNSHelper}"""
Exit 1
} }
+158
View File
@@ -0,0 +1,158 @@
#Requires -Version 5.1
# Read-only endpoint investigation. Creates a diagnostic ZIP; never runs Office,
# changes its registry, stops workers, or imports the deployment script.
# Run elevated, directly or through rmm/Get-OfficeDeploymentDiagnostics.ps1.
function Get-OfficeDiagnosticFiles {
param([string]$Root, [string[]]$Patterns, [datetime]$SinceUtc, [int]$Depth = 0, $Issues)
try {
if (!(Test-Path -LiteralPath $Root -ErrorAction Stop)) { return }
$item = Get-Item -LiteralPath $Root -ErrorAction Stop
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { return }
foreach ($child in @(Get-ChildItem -LiteralPath $Root -Force -ErrorAction Stop)) {
if ($child.Attributes -band [IO.FileAttributes]::ReparsePoint) { continue }
if ($child.PSIsContainer) {
if ($Depth -gt 0) { Get-OfficeDiagnosticFiles $child.FullName $Patterns $SinceUtc ($Depth - 1) $Issues }
} elseif ($child.LastWriteTimeUtc -ge $SinceUtc) {
foreach ($pattern in $Patterns) { if ($child.Name -like $pattern) { $child; break } }
}
}
} catch { $Issues.Add("File enumeration: $Root : $($_.Exception.Message)") }
}
function Get-OfficeDiagnosticRegistry {
# Explicit views also work when Syncro runs 32-bit PowerShell. Do not export
# licensing/identity stores or use Win32_Product (which can trigger repairs).
foreach ($view in @([Microsoft.Win32.RegistryView]::Registry64, [Microsoft.Win32.RegistryView]::Registry32)) {
$base = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $view)
try {
$queue = New-Object 'Collections.Generic.Queue[string]'
$queue.Enqueue('SOFTWARE\Microsoft\Office\ClickToRun')
while ($queue.Count) {
$path = $queue.Dequeue(); $key = $base.OpenSubKey($path, $false)
if (!$key) { continue }
try {
foreach ($name in $key.GetValueNames()) {
$value = $key.GetValue($name)
if ($name -match '^(WorkingConfig(uration)?|SourcePath|InstallationPath|InstallPath|ProductReleaseIds|VersionToReport|ClientVersionToReport|Platform|CDNBaseUrl|UpdateChannel|UpdateUrl|UpdatePath|AudienceId)$' -or
($value -is [string] -and $value -match '(?i)EmberkomOfficeDeployment[\\/]')) {
[pscustomobject]@{ View=[string]$view; Key=$path; Name=$name; Value=$value }
}
}
foreach ($child in $key.GetSubKeyNames()) { $queue.Enqueue("$path\$child") }
} finally { $key.Dispose() }
}
$uninstall = $base.OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', $false)
if ($uninstall) {
try {
foreach ($name in $uninstall.GetSubKeyNames()) {
$key = $uninstall.OpenSubKey($name, $false)
if (!$key) { continue }
try {
$display = $key.GetValue('DisplayName')
if ($display -match '(?i)^(Microsoft\s+)?(365|Office|Visio|Project|Access|Word|Excel|Outlook|PowerPoint|OneNote|Publisher|Skype for Business)(\s|$)') {
[pscustomobject]@{ View=[string]$view; Key=$key.Name; DisplayName=$display; DisplayVersion=$key.GetValue('DisplayVersion'); Publisher=$key.GetValue('Publisher'); WindowsInstaller=$key.GetValue('WindowsInstaller'); InstallLocation=$key.GetValue('InstallLocation') }
}
} finally { $key.Dispose() }
}
} finally { $uninstall.Dispose() }
}
} finally { $base.Dispose() }
}
}
function Add-OfficeDiagnosticText {
param($Archive, [string]$Name, [string]$Text)
$stream = $Archive.CreateEntry($Name).Open()
$writer = New-Object IO.StreamWriter($stream, (New-Object Text.UTF8Encoding($false)))
try { $writer.Write($Text) } finally { $writer.Dispose() }
}
function New-OfficeDiagnosticArchive {
param([string]$Path, [object[]]$Files, $Report, $Issues)
Add-Type -AssemblyName System.IO.Compression -ErrorAction Stop
$output = [IO.File]::Open($Path, [IO.FileMode]::CreateNew, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None)
$archive = $null; $total = 0L; $manifest = New-Object 'Collections.Generic.List[object]'
try {
$archive = New-Object IO.Compression.ZipArchive($output, [IO.Compression.ZipArchiveMode]::Create, $true)
foreach ($file in @($Files | Sort-Object FullName -Unique | Sort-Object LastWriteTimeUtc -Descending)) {
$row = [pscustomobject]@{ Source=$file.FullName; LastWriteTimeUtc=$file.LastWriteTimeUtc; Length=$file.Length; Entry=$null; CapturedBytes=0L; Status='Pending' }
$manifest.Add($row)
$inputStream = $null; $entryStream = $null
try {
if ($file.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Reparse points are excluded.' }
$inputStream = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, ([IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete))
$length = $inputStream.Length
if ($length -gt 64MB -or ($total + $length) -gt 512MB -or $manifest.Count -gt 2000) { throw 'Collection limit reached (64 MB/file, 512 MB total, 2000 files); source was not changed.' }
$row.Entry = 'files/{0:D4}_{1}' -f $manifest.Count, $file.Name
$entryStream = $archive.CreateEntry($row.Entry, [IO.Compression.CompressionLevel]::Optimal).Open()
$buffer = New-Object byte[] 65536
# Bound the copy to its initial length even if a live log grows.
while ($row.CapturedBytes -lt $length) {
$read = $inputStream.Read($buffer, 0, [int][Math]::Min($buffer.Length, $length - $row.CapturedBytes))
if (!$read) { throw 'Source changed/truncated during capture.' }
$entryStream.Write($buffer, 0, $read); $row.CapturedBytes += $read; $total += $read
}
$row.Status = 'Captured (live files are not an atomic snapshot)'
} catch { $row.Status = "Incomplete: $($_.Exception.Message)"; $Issues.Add("$($row.Source) : $($row.Status)") }
finally { if ($entryStream) { $entryStream.Dispose() }; if ($inputStream) { $inputStream.Dispose() } }
}
Add-OfficeDiagnosticText $archive 'endpoint.json' ($Report | ConvertTo-Json -Depth 10)
Add-OfficeDiagnosticText $archive 'manifest.json' (ConvertTo-Json -InputObject @($manifest.ToArray()) -Depth 5)
Add-OfficeDiagnosticText $archive 'collection-issues.json' (ConvertTo-Json -InputObject @($Issues.ToArray()))
Add-OfficeDiagnosticText $archive 'README.txt' 'Read-only evidence bundle. endpoint.json is CURRENT state, not the state before the manual install. Use original timestamps inside native logs to compare runs. manifest.json maps archived files to their original paths. Read collection-issues.json for omissions. No Office media is archived or executed. Logs may contain user names and paths.'
} finally { if ($archive) { $archive.Dispose() }; $output.Dispose() }
}
function Invoke-OfficeDiagnosticCollection {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
if (!(New-Object Security.Principal.WindowsPrincipal($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run the diagnostic collector elevated or as SYSTEM.' }
$since = [datetime]::UtcNow.AddHours(-72)
$issues = New-Object 'Collections.Generic.List[string]'
$files = New-Object 'Collections.Generic.List[object]'
$report = [ordered]@{ CollectedUtc=[datetime]::UtcNow; SinceUtc=$since; Computer=$env:COMPUTERNAME; Identity=$identity.Name; ProcessId=$PID; Is64BitProcess=[Environment]::Is64BitProcess; PowerShellVersion=[string]$PSVersionTable.PSVersion; TimeZone=[TimeZoneInfo]::Local.Id }
try { $report.OS = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop | Select-Object Caption, Version, BuildNumber, LastBootUpTime } catch { $issues.Add("OS: $($_.Exception.Message)") }
try { $profiles = @(Get-CimInstance Win32_UserProfile -ErrorAction Stop | Select-Object SID, LocalPath, Loaded, Special); $report.Profiles = $profiles } catch { $profiles=@(); $issues.Add("Profiles: $($_.Exception.Message)") }
try { $report.OfficeRegistry = @(Get-OfficeDiagnosticRegistry) } catch { $issues.Add("Registry: $($_.Exception.Message)") }
try { $report.ClickToRunService = Get-CimInstance Win32_Service -Filter "Name='ClickToRunSvc'" -ErrorAction Stop | Select-Object Name, State, StartMode, ProcessId, PathName } catch { $issues.Add("Service: $($_.Exception.Message)") }
try {
$report.Workers = @(Get-CimInstance Win32_Process -ErrorAction Stop | Where-Object {
$_.Name -match '^(setup|OfficeClickToRun|OfficeC2RClient|GetHelpCmd|SaRAcmd|msiexec|cscript|wscript)\.exe$' -or $_.CommandLine -match '(?i)OfficeScrub|OffScrub|GetHelpElevated|EmberkomOfficeDeployment'
} | ForEach-Object {
$worker = $_ | Select-Object Name, ProcessId, ParentProcessId, SessionId, CreationDate, ExecutablePath, CommandLine
try { $owner = Invoke-CimMethod -InputObject $_ -MethodName GetOwner -ErrorAction Stop; $worker | Add-Member NoteProperty Owner "$($owner.Domain)\$($owner.User)"; $worker | Add-Member NoteProperty OwnerQueryResult $owner.ReturnValue } catch { $issues.Add("Process owner PID $($worker.ProcessId): $($_.Exception.Message)") }
$worker
})
} catch { $issues.Add("Workers: $($_.Exception.Message)") }
try { $report.CleanupTasks = @(Get-ScheduledTask -TaskName 'Emberkom-OfficeCleanup-*' -ErrorAction Stop | Select-Object TaskName, State, Principal, Actions) } catch { $issues.Add("Cleanup tasks (possibly none): $($_.Exception.Message)") }
$nativeWindows = if ([Environment]::Is64BitOperatingSystem -and ![Environment]::Is64BitProcess) { Join-Path $env:windir 'Sysnative' } else { Join-Path $env:windir 'System32' }
$tempRoots = @($env:TEMP, "$env:windir\Temp", "$env:windir\SystemTemp") + @($profiles | ForEach-Object { Join-Path $_.LocalPath 'AppData\Local\Temp' })
foreach ($root in @($tempRoots | Select-Object -Unique)) {
foreach ($file in @(Get-OfficeDiagnosticFiles $root @("$env:COMPUTERNAME*.log", 'Office*.log', 'Microsoft*Office*.log', 'ClickToRun*.log', 'Setup*.log', 'OffScrub*.log', 'OffScrub*.txt') $since 0 $issues)) { $files.Add($file) }
foreach ($file in @(Get-OfficeDiagnosticFiles (Join-Path $root 'EmberkomOfficeDeployment') @('*.log', 'install.xml', 'remove.xml') $since 3 $issues)) { $files.Add($file) }
# Worker scripts carry Microsoft's package timestamps, so do not filter them by LastWriteTime.
foreach ($file in @(Get-OfficeDiagnosticFiles (Join-Path $root 'GetHelpElevated') @('Run.ps1', 'OfficeUninstall.ps1', 'Logger-FileLogUtils.ps1', 'Utils.ps1', 'Env-Utils.ps1') ([datetime]::MinValue) 1 $issues)) { $files.Add($file) }
}
$localRoots = @($env:LOCALAPPDATA, "$nativeWindows\config\systemprofile\AppData\Local", "$env:windir\SysWOW64\config\systemprofile\AppData\Local") + @($profiles | ForEach-Object { Join-Path $_.LocalPath 'AppData\Local' })
foreach ($root in @($localRoots | Select-Object -Unique)) {
foreach ($file in @(Get-OfficeDiagnosticFiles (Join-Path $root 'DAFs') @('*office*uninstall*.log', '*uninstall*office*.log') $since 2 $issues)) { $files.Add($file) }
}
foreach ($file in @(Get-OfficeDiagnosticFiles "$env:ProgramData\EmberkomOfficeDeployment" @('*.log') $since 3 $issues)) { $files.Add($file) }
foreach ($file in @(Get-OfficeDiagnosticFiles "$env:ProgramData\Emberkom\Logs" @('ManagementScript_*.log') $since 0 $issues)) {
try {
if ($file.Length -gt 64MB) { $issues.Add("Management log exceeds 64 MB filter limit: $($file.FullName)"); continue }
if (Select-String -LiteralPath $file.FullName -Pattern 'Install-MicrosoftOffice365', 'EmberkomOfficeDeployment' -SimpleMatch -Quiet -ErrorAction Stop) { $files.Add($file) }
}
catch { $issues.Add("Management log filter: $($file.FullName) : $($_.Exception.Message)") }
}
$destination = Join-Path $env:ProgramData 'Emberkom\Logs\OfficeDiagnostics'
$null = New-Item -ItemType Directory -Path $destination -Force -ErrorAction Stop
$zip = Join-Path $destination ('OfficeDiagnostics-{0}-{1}-{2}.zip' -f $env:COMPUTERNAME, (Get-Date -Format 'yyyyMMdd-HHmmss'), [guid]::NewGuid().ToString('N').Substring(0,8))
New-OfficeDiagnosticArchive $zip @($files.ToArray()) $report $issues
Write-Output "Office diagnostic ZIP: $zip"
Write-Output "Collection issues: $($issues.Count). Review collection-issues.json for missing/unreadable files. Office installation and running processes were not changed."
}
try { Invoke-OfficeDiagnosticCollection }
catch { Write-Error "Office diagnostic collection failed: $($_.Exception.Message)" -ErrorAction Continue; exit 1 }
+8 -36
View File
@@ -1,15 +1,8 @@
# Specify URL to "Backup for Windows" agent installer # Install and update use the same published Emberkom packages.
$ECB_WIN_URL = 'https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWTBzNG1zVDV0ckVMdStZVzBsam5uZklMVnZLeTBMVmxGNWt4VDhSMzNIL3VmK3VHNmxBVEZTQkxhMFhNR2ZuZzJCeE80MDJxVkRSWXdNa0dqSHdpbUN1bE01c3BWNFBVUmt2Q1c4endncjVZemFSSjEyYmFNL3hESHR2eWpVYXpBVlV2eU1kZVZFaEpvalk2Rk40Wk96UG9QdUwxYnZrRHREMmhLeTZoMW5Rbz0*&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4' switch ($Edition) {
'server' { $CloudBackupBuild = 'Windows'; $AgentEdition = 'baremetal' }
# Specify URL to "Backup Virtual Machine Edition" agent installer 'vm' { $CloudBackupBuild = 'VM'; $AgentEdition = 'vmedition' }
$ECB_VMM_URL = 'https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWUpYM2xDY3ErMkpOVGpuWTRISDNFcFRFdWRibDgvTm8vUDhpWndON3kzaHNwOTFVa3h6WUdoeVVod1JmT2lRQ1FlVTE3Y0pnUncwSEJwS3FFcDBmTWt3cEdnSy9YemRsSTRiQWJHNi96cUtWbzZsc25QVllaR1QyQ21VVS95dFFVTkNndXdPVStGQXBIT0FZb2FIUzFuZy9mMU5qZUd5emhab1hFYjZWODB4ND0*&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4' default { $CloudBackupBuild = 'Windows'; $AgentEdition = 'desktop' }
# Set the correct download URL and agent edition
switch ( $Edition.ToLower() ) {
'server' { $URL = $ECB_WIN_URL; $AgentEdition = 'baremetal' }
'desktop' { $URL = $ECB_WIN_URL; $AgentEdition = 'desktop' }
'vm' { $URL = $ECB_VMM_URL; $AgentEdition = 'vmedition' }
default { $URL = $ECB_WIN_URL; $AgentEdition = 'desktop' }
} }
# Install and import additional Powershell module # Install and import additional Powershell module
@@ -21,30 +14,9 @@ If ( $(Get-MBSAgent -ErrorAction SilentlyContinue) ) {
Return Return
} }
# $CloudBackupRelease = Get-EmberkomCloudBackupRelease -Build $CloudBackupBuild
# The URL is now too long to pass as a variable to other functions and cmdlets, so this is a workaround to download the file $Installer = Join-Path (Get-TempPath) ("EmberkomCloudBackup-{0}.exe" -f [guid]::NewGuid())
# Save-EmberkomCloudBackupInstaller -Release $CloudBackupRelease -Path $Installer
# Make sure the URL is valid
$StatusCode = [System.Net.WebRequest]::Create($URL).GetResponse().StatusCode
If ( !(($StatusCode -ge 200) -and ($StatusCode -lt 400)) ) { Write-Output "URL cannot be reached (status code ${StatusCode}): ${URL}" ; Return }
# Make a local file to download to
$Installer = '{0}EmberkomCloudBackup.exe' -f (Get-TempPath)
# Delete previous local file if it exists
If ( Test-Path $Installer ) { Write-Output "Deleting previously downloaded file: ${Installer}" ; Remove-Item $Installer -Force -ErrorAction SilentlyContinue }
# Download the file
Try { (New-Object System.Net.WebClient).DownloadFile($URL,$Installer) }
Catch { Write-Error $_.Exception.Message ; Remove-Item $Installer -Force -ErrorAction SilentlyContinue }
# Make sure the file exists
If ( !(Test-Path $Installer) ) { Write-Output "There was a problem downloading the file, this script will not continue" ; Return }
#
# End the workaround
#
# Install the agent # Install the agent
Write-Output "Installing Emberkom Cloud Backup agent" Write-Output "Installing Emberkom Cloud Backup agent"
+553 -190
View File
@@ -32,7 +32,24 @@ function Get-OfficeDeploymentDefinitions {
OdtPage = 'https://www.microsoft.com/en-us/download/details.aspx?id=49117' OdtPage = 'https://www.microsoft.com/en-us/download/details.aspx?id=49117'
OdtDownloadPattern = 'https://download\.microsoft\.com/[^"\s<>]+/officedeploymenttool_[a-zA-Z0-9_-]+\.exe' OdtDownloadPattern = 'https://download\.microsoft\.com/[^"\s<>]+/officedeploymenttool_[a-zA-Z0-9_-]+\.exe'
ManualScrubUrl = 'https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall' ManualScrubUrl = 'https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall'
HelperVersion = 'EmberkomOfficeUserCleanup-v4' GetHelpUrl = 'https://aka.ms/SaRA_EnterpriseVersionFiles'
GetHelpExecutable = 'GetHelpCmd.exe'
# Probe each fresh download's usage; add OfficeVersion only when advertised.
ScrubArguments = '-S OfficeScrubScenario -AcceptEula'
ScrubAllVersionsArgument = '-OfficeVersion All'
ScrubHelpPattern = '(?im)^\s*GetHelpCmd\.exe\s+-S\s+OfficeScrubScenario\s+-AcceptEula(?:\s|$)'
ScrubVersionSwitchPattern = '(?im)^\s*-OfficeVersion\b'
ScrubTextSuccessPattern = '(?im)^\s*Scenario completed successfully\.\s*$'
ScrubBackgroundPattern = '(?im)^\s*ExecutionResultDetails:\s*Uninstall office is running in the background\.'
ScrubFailurePattern = '(?im)^\s*(?:Error\s*:|(?:-\s*)?Uninstall Office Scenario failed\.|The scenario requires an elevated command-prompt\.)'
ScrubBackgroundCheckAttempts = 181
ScrubBackgroundCheckSeconds = 10
ScrubBackgroundQuietChecks = 7
ScrubWorkerNames = @('powershell.exe', 'pwsh.exe', 'cscript.exe', 'wscript.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'OfficeClickToRun.exe', 'setup.exe', 'integratedoffice.exe', 'GetHelpCmd.exe', 'SaRAcmd.exe')
ScrubRecoveryExitCodes = @(17002, 17004)
ScrubDiagnosticLineLimit = 20
ScrubDiagnosticLineCharacters = 2000
HelperVersion = 'EmberkomOfficeUserCleanup-v5'
Language = 'en-us' Language = 'en-us'
OfficeBuildPattern = '^16\.0\.\d+\.\d+$' OfficeBuildPattern = '^16\.0\.\d+\.\d+$'
OdtExcludedApps = @('Groove', 'OneDrive', 'Lync', 'Teams', 'OutlookForWindows') OdtExcludedApps = @('Groove', 'OneDrive', 'Lync', 'Teams', 'OutlookForWindows')
@@ -61,6 +78,11 @@ function Get-OfficeDeploymentDefinitions {
MonthlyEnterprise = 'monthly-enterprise-channel' MonthlyEnterprise = 'monthly-enterprise-channel'
SemiAnnual = 'semi-annual-enterprise-channel' SemiAnnual = 'semi-annual-enterprise-channel'
} }
OfficeCdnChannels = @{
Current = '492350f6-3a01-4f97-b9c0-c7c6ddf67d60'
MonthlyEnterprise = '55336b82-a18d-4dd6-b5f6-9e5095c314a6'
SemiAnnual = '7ffbc6bf-bc32-4f92-8982-f9dd17fd3114'
}
TeamsUnsupportedWindows10Editions = @('EnterpriseS', 'EnterpriseSN', 'IoTEnterpriseS') TeamsUnsupportedWindows10Editions = @('EnterpriseS', 'EnterpriseSN', 'IoTEnterpriseS')
# Teams.exe is classic, msteams.exe is the older personal/Windows Chat client, # Teams.exe is classic, msteams.exe is the older personal/Windows Chat client,
# and ms-teams.exe is the current client. Check all three before removal. # and ms-teams.exe is the current client. Check all three before removal.
@@ -83,7 +105,6 @@ function Get-OfficeDeploymentDefinitions {
AppxRemovalAttempts = 3 AppxRemovalAttempts = 3
UserCleanupWaitMinutes = 20 UserCleanupWaitMinutes = 20
UserCleanupTaskMinutes = 30 UserCleanupTaskMinutes = 30
MediaCacheDays = 7
# Deployment headroom, not Microsoft's published minimum system requirements. # Deployment headroom, not Microsoft's published minimum system requirements.
# Reserve installation/companion space in addition to a fresh media download. # Reserve installation/companion space in addition to a fresh media download.
MinimumInstallFreeSpaceGB = 10 MinimumInstallFreeSpaceGB = 10
@@ -193,6 +214,7 @@ function New-OfficeWorkspace {
) )
# Executable content must never be writable by a standard user. # Executable content must never be writable by a standard user.
# Default to the execution account's temp location (SYSTEM under Syncro). # Default to the execution account's temp location (SYSTEM under Syncro).
Assert-OfficeManagedPath $root (Join-Path $root $DeploymentId)
$null = New-Item -ItemType Directory -Path $root -Force -ErrorAction Stop $null = New-Item -ItemType Directory -Path $root -Force -ErrorAction Stop
for ($item = Get-Item -LiteralPath $root -Force; $null -ne $item; $item = $item.Parent) { 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)" } if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Deployment path traverses a reparse point: $($item.FullName)" }
@@ -214,15 +236,60 @@ function New-OfficeWorkspace {
function New-OfficeUserWorkspace { function New-OfficeUserWorkspace {
param($Media, [string]$Workspace) param($Media, [string]$Workspace)
# Only deferred user cleanup must survive routine temp purges. SYSTEM's temp # Persist only synchronization state for deferred tasks. They fetch code live;
# directory may also be inaccessible to the limited users who run this helper. # no downloaded helper or installation payload survives in ProgramData.
$path = New-OfficeWorkspace -Root (Join-Path $env:ProgramData 'EmberkomOfficeDeployment') -DeploymentId (Split-Path -Leaf $Workspace) $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 $path
} }
function Assert-OfficeWritablePath {
param([string]$Path)
$target = [IO.Path]::GetFullPath($Path)
# Probe the closest existing parent without creating the intended directory.
$parent = $target
while (!(Test-Path -LiteralPath $parent)) {
$parent = Split-Path -Parent $parent
if (!$parent) { throw "No existing parent for deployment path: $target" }
}
Assert-OfficeManagedPath $parent (Join-Path $parent 'office-write-probe')
if (!(Test-Path -LiteralPath $parent -PathType Container)) { throw "Deployment parent is not a directory: $parent" }
$probePath = Join-Path $parent ('OfficeWriteProbe-' + [guid]::NewGuid().ToString('N') + '.tmp')
$probe = $null
try {
$probe = [IO.FileStream]::new($probePath, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None, 1, [IO.FileOptions]::DeleteOnClose)
} catch { throw "Deployment path is not writable: $target (tested $parent). $($_.Exception.Message)" }
finally { if ($probe) { $probe.Dispose() } }
$null = Write-Output "Writable path verified: $target (tested existing directory $parent)."
[pscustomobject]@{ Path=$target; TestedDirectory=$parent }
}
function Test-OfficeDownloadLinks {
param($Options)
$definitions = Get-OfficeDeploymentDefinitions
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$links = @($definitions.OdtPage, "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1", $definitions.GetHelpUrl)
if ($Options.OfficeFeatureRelease) { $links += $definitions.OfficeReleaseHistory }
$channel = $definitions.OfficeCdnChannels[$Options.UpdateChannel]
$links += "https://officecdn.microsoft.com/pr/$channel/Office/Data/v$($Options.OfficeArchitecture).cab"
foreach ($name in @('WebView2', 'NewOutlook', 'OneDrive', 'Teams')) {
if ($name -eq 'Teams' -and !$Options.InstallTeams) { continue }
$installer = $definitions.CompanionInstallers[$name]
if ($name -eq 'OneDrive') {
$arch = if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64' -or $env:PROCESSOR_ARCHITEW6432 -eq 'ARM64') { 'ARM64' } elseif ([Environment]::Is64BitOperatingSystem) { 'x64' } else { 'x86' }
$links += $installer.Uris[$arch]
} else { $links += $installer.Uri }
}
foreach ($uri in $links) {
# HEAD follows redirects but never requests a body or writes a download.
# A server that refuses HEAD fails assessment; do not fall back to GET.
try { $response = Invoke-WebRequest -UseBasicParsing -Method Head -Uri $uri -MaximumRedirection 10 -TimeoutSec $definitions.OdtPageTimeoutSeconds -ErrorAction Stop }
catch { throw "HTTP HEAD check failed for $uri. $($_.Exception.Message)" }
if ([int]$response.StatusCode -ne 200) { throw "HTTP HEAD check for $uri returned $($response.StatusCode); expected 200." }
$null = Write-Output "HTTP HEAD 200: $uri"
[pscustomobject]@{ Uri=$uri; StatusCode=200; Method='HEAD' }
}
}
function Assert-OfficeManagedPath { function Assert-OfficeManagedPath {
param([string]$Root, [string]$Path) param([string]$Root, [string]$Path)
$base = [IO.Path]::GetFullPath($Root).TrimEnd('\') $base = [IO.Path]::GetFullPath($Root).TrimEnd('\')
@@ -257,12 +324,6 @@ function Remove-OfficeManagedItem {
Remove-Item -LiteralPath ([IO.Path]::GetFullPath($Path)) -Recurse -Force -ErrorAction Stop Remove-Item -LiteralPath ([IO.Path]::GetFullPath($Path)) -Recurse -Force -ErrorAction Stop
} }
function Get-OfficeStagingNames {
# Only our downloaded artifacts; never Office's installed files or servicing caches.
@('ODT', 'odt.exe', 'odt-download-page.html', 'GetHelp', 'GetHelp.zip', 'media-cache.json')
foreach ($installer in (Get-OfficeDeploymentDefinitions).CompanionInstallers.Values) { $installer.File }
}
function Assert-OfficeDiskSpace { function Assert-OfficeDiskSpace {
param( param(
[string]$Workspace, [string]$Workspace,
@@ -288,7 +349,7 @@ function Assert-OfficeDiskSpace {
$stage = if ($DownloadingMedia) { 'before downloading media' } else { 'after staging, before removal' } $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." $null = Write-Output "Office disk-space check ${stage}: $drive has $availableGB GB free; deployment requires $requiredGB GB."
if ([long]$disk.FreeSpace -lt $required[$drive]) { 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 +357,113 @@ function Assert-OfficeDiskSpace {
function Remove-OfficeStagingFiles { function Remove-OfficeStagingFiles {
param([string]$Root, [string]$Workspace) param([string]$Root, [string]$Workspace)
Assert-OfficeManagedPath $Root $Workspace Assert-OfficeManagedPath $Root $Workspace
foreach ($name in (Get-OfficeStagingNames)) { Remove-OfficeManagedItem $Root (Join-Path $Workspace $name) } $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.
$files = @(Get-OfficeManagedFiles $Root $Workspace | Where-Object { $_.Extension -notin @('.log', '.etl') })
foreach ($file in $files) {
$probe = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
$probe.Dispose()
}
foreach ($file in $files) { Remove-OfficeManagedItem $Root $file.FullName }
# Preserve nested logs and their parents, but discard empty payload folders.
foreach ($folder in @(Get-ChildItem -LiteralPath $Workspace -Directory -Recurse -Force -ErrorAction Stop | Sort-Object { $_.FullName.Length } -Descending)) {
Assert-OfficeManagedPath $Root $folder.FullName
if (!@(Get-ChildItem -LiteralPath $folder.FullName -Force -ErrorAction Stop).Count) { Remove-Item -LiteralPath $folder.FullName -Force -ErrorAction Stop }
}
}
function Get-OfficeDeploymentRoots {
$parents = @([IO.Path]::GetTempPath(), (Join-Path $env:WINDIR 'Temp'), (Join-Path $env:WINDIR 'SystemTemp'), $env:ProgramData)
foreach ($profile in @(Get-CimInstance Win32_UserProfile -ErrorAction Stop)) {
if ($profile.LocalPath) { $parents += Join-Path $profile.LocalPath 'AppData\Local\Temp' }
}
@($parents | Where-Object { $_ } | ForEach-Object { [IO.Path]::GetFullPath((Join-Path $_ 'EmberkomOfficeDeployment')).TrimEnd('\') } | Sort-Object -Unique)
}
function Clear-OfficePreviousDeploymentFiles {
# The deployment mutex is held by the caller. Never import options, XML or media
# from these folders; the reserved root and GUID identify our prior workspaces.
$roots = @(Get-OfficeDeploymentRoots)
$processes = @(Get-CimInstance Win32_Process -ErrorAction Stop)
foreach ($root in $roots) {
$blocking = @(Get-OfficeBlockingProcesses $root $processes)
if ($blocking.Count) { throw "A surviving installer is running: $(($blocking | ForEach-Object { "$($_.Name) (PID $($_.ProcessId))" }) -join '; '). Resolve the previous deployment before removing old artifacts in $root. GetHelpElevated Run.ps1 can remain at a 'Press any key to exit' prompt after success or failure; inspect its final report before dismissing it." }
Assert-OfficeManagedPath $root (Join-Path $root 'path-check')
}
$tasks = @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -match '^Emberkom-OfficeCleanup-[a-f0-9]{32}-S-1-[\d-]+$' })
if (@($tasks | Where-Object { $_.State -in @('Running', 'Queued') }).Count) { throw 'Previous Office user cleanup is still running. Wait for it to finish before redeploying.' }
foreach ($task in $tasks) {
$null = Disable-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -ErrorAction Stop
if ((Get-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -ErrorAction Stop).State -in @('Running', 'Queued')) { throw "Previous user cleanup started during preparation: $($task.TaskName)." }
Unregister-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -Confirm:$false -ErrorAction Stop
$null = Write-Output "Retired previous user cleanup task; this deployment will schedule fresh cleanup: $($task.TaskName)"
}
foreach ($root in $roots) {
# Older validation runs wrote release metadata beside the staging root.
# New runs keep it inside their GUID workspace, including partial downloads.
$parent = Split-Path -Parent $root
if (Test-Path -LiteralPath $parent -PathType Container) {
foreach ($file in @(Get-ChildItem -LiteralPath $parent -File -Filter 'OfficeReleaseHistory-*.html' -ErrorAction Stop | Where-Object { $_.Name -match '^OfficeReleaseHistory-[a-f0-9]{32}\.html$' })) {
Assert-OfficeManagedPath $parent $file.FullName
$probe = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
$probe.Dispose()
Remove-OfficeManagedItem $parent $file.FullName
}
}
if (!(Test-Path -LiteralPath $root)) { continue }
foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -Force -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' })) {
Remove-OfficeStagingFiles $root $folder.FullName
if (!@(Get-ChildItem -LiteralPath $folder.FullName -Force -ErrorAction Stop).Count) { Remove-OfficeManagedItem $root $folder.FullName }
}
}
}
function Get-OfficeBlockingProcesses {
param([string]$Workspace, [object[]]$Processes)
# Be conservative even when a child installer no longer names its source folder.
foreach ($process in $Processes) {
# Windows Installer service/server hosts can remain after their clients exit.
if ($process.Name -eq 'msiexec.exe' -and $process.CommandLine -match '(?i)\s/(V|Embedding)(?:\s|$)') { continue }
if ($process.Name -in @('setup.exe', 'odt.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'GetHelpCmd.exe', 'SaRAcmd.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe')) { $process; continue }
if ($process.Name -eq 'OfficeClickToRun.exe' -and $process.CommandLine -notmatch '(?i)\s/(service|user)\s*$') { $process; continue }
if ($process.CommandLine -match '(?i)\b(OffScrub[^\s"\\/]*\.(vbs|ps1)|OfficeScrubScenario)\b') { $process; continue }
# Current Get Help detaches PowerShell into its own temp directory. Its
# command line contains neither OfficeScrubScenario nor our workspace.
if ($process.CommandLine -match '(?i)[\\/]GetHelpElevated[\\/][^\\/"\s]+[\\/]Run\.ps1(?:["\s]|$)') { $process; continue }
foreach ($value in @($process.CommandLine, $process.ExecutablePath)) {
if ($Workspace -and $value -and $value.IndexOf($Workspace, [StringComparison]::OrdinalIgnoreCase) -ge 0) { $process; break }
}
}
}
function Test-OfficeStagingInUse {
param([string]$Workspace, [object[]]$Processes)
return @(Get-OfficeBlockingProcesses $Workspace $Processes).Count -gt 0
} }
function Complete-OfficeDeploymentFiles { function Complete-OfficeDeploymentFiles {
param([string]$Workspace, [string]$UserWorkspace, [string]$PreviousRoot) param([string]$Workspace, [string]$UserWorkspace)
$warnings = @() $warnings = @()
# This runs only after installation succeeds. No scheduled housekeeping is created. # Called from finally on success, failure and restart exits. Only logs remain
# Include older temp attempts, but never files still referenced by another process. # in the download workspace after native processes release it.
$root = Split-Path -Parent $Workspace try {
$processes = @(Get-CimInstance Win32_Process -ErrorAction Stop) $root = Split-Path -Parent $Workspace
foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' })) { Remove-OfficeStagingFiles $root $Workspace
try { } catch {
Assert-OfficeManagedPath $root $folder.FullName $warnings += "$Workspace : $($_.Exception.Message)"
if (!(Test-Path -LiteralPath (Join-Path $folder.FullName 'options.json'))) { continue } Write-Error "Deployment media cleanup deferred: $($warnings[-1])" -ErrorAction 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
}
}
} }
# Pending tasks need only their lock and phase marker, not downloaded code.
if ($UserWorkspace -and $UserWorkspace -ne $Workspace) { if ($UserWorkspace -and $UserWorkspace -ne $Workspace) {
try { try {
# Start-OfficeUserCleanup already unregisters completed tasks. Preserve the
# helper whenever any task remains, including a failed unregister attempt.
$id = Split-Path -Leaf $UserWorkspace $id = Split-Path -Leaf $UserWorkspace
$tasks = @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -like "Emberkom-OfficeCleanup-$id-*" }) $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 { } catch {
$warnings += "$UserWorkspace : $($_.Exception.Message)" $warnings += "$UserWorkspace : $($_.Exception.Message)"
Write-Error "Could not remove completed user cleanup files: $($warnings[-1])" -ErrorAction Continue Write-Error "Could not remove completed user cleanup files: $($warnings[-1])" -ErrorAction Continue
@@ -350,84 +472,22 @@ function Complete-OfficeDeploymentFiles {
return ,$warnings return ,$warnings
} }
function Get-OfficeMediaCacheKey { function Resolve-OfficeTargetVersion {
param($Options) param($Options, [Parameter(Mandatory=$true)][string]$Workspace)
$Options.TargetOfficeVersion = ''
if (!$Options.OfficeFeatureRelease) { return }
$definitions = Get-OfficeDeploymentDefinitions $definitions = Get-OfficeDeploymentDefinitions
# Company, activation, app shutdown, and reboot choices affect XML, not the payload. [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$contract = [ordered]@{ # Deployment only. Assessment checks HEAD without resolving/downloading metadata.
Schema=2; Product=$Options.ProductId; Architecture=$Options.OfficeArchitecture $historyPath = Join-Path $Workspace 'office-release-history.html'
Channel=$Options.UpdateChannel; Language=$definitions.Language try {
TargetVersion=$Options.TargetOfficeVersion Save-OfficeDownload $definitions.OfficeReleaseHistory $historyPath
OdtPage=$definitions.OdtPage; ExcludedApps=$definitions.OdtExcludedApps $Options.TargetOfficeVersion = Get-OfficeBuildFromHistory (Get-Content -LiteralPath $historyPath -Raw -ErrorAction Stop) $Options.UpdateChannel $Options.OfficeFeatureRelease
Downloads=@(Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams | ForEach-Object { "$($_.Name)|$($_.File)|$($_.Uri)" }) $null = Write-Output "Windows 10: selected Office $($Options.OfficeFeatureRelease), build $($Options.TargetOfficeVersion), from Microsoft's $($Options.UpdateChannel) release history."
} } finally {
$contract | ConvertTo-Json -Depth 5 -Compress if (Test-Path -LiteralPath $historyPath) { Remove-Item -LiteralPath $historyPath -Force -ErrorAction Stop }
}
function Save-OfficeMediaCache {
param($Options, $Media, [string]$Workspace, [string]$CreatedUtc = ([DateTime]::UtcNow.ToString('o')))
$root = Split-Path -Parent $Workspace
$files = @()
foreach ($name in @('ODT', 'odt.exe') + @(Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams | ForEach-Object { $_.File })) {
foreach ($file in @(Get-OfficeManagedFiles $root (Join-Path $Workspace $name))) {
$files += [pscustomobject]@{ Path=$file.FullName.Substring($Workspace.TrimEnd('\').Length + 1); Length=$file.Length }
}
}
[ordered]@{ Schema=2; Key=(Get-OfficeMediaCacheKey $Options); CreatedUtc=$CreatedUtc; Version=$Media.Version; Files=$files } |
ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $Workspace 'media-cache.json') -Encoding UTF8 -ErrorAction Stop
}
function Restore-OfficeMediaCache {
param($Options, [string]$Workspace)
$root = Split-Path -Parent $Workspace
$definitions = Get-OfficeDeploymentDefinitions
$key = Get-OfficeMediaCacheKey $Options
foreach ($candidate in @(Get-ChildItem -LiteralPath $root -Directory -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' -and $_.FullName -ne $Workspace } | Sort-Object LastWriteTimeUtc -Descending)) {
$manifestPath = Join-Path $candidate.FullName 'media-cache.json'
if (!(Test-Path -LiteralPath $manifestPath)) { continue }
$inUse = @(Get-CimInstance Win32_Process -ErrorAction Stop | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($candidate.FullName, [StringComparison]::OrdinalIgnoreCase) -ge 0 })
if ($inUse.Count) { throw "A previous Office deployment still has active processes using $($candidate.FullName). Wait for them to finish before retrying." }
try {
Assert-OfficeManagedPath $root $manifestPath
$manifest = Get-Content -LiteralPath $manifestPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
$created = [DateTime]::Parse($manifest.CreatedUtc).ToUniversalTime()
if ($manifest.Schema -ne 2 -or $manifest.Key -ne $key -or $created -gt [DateTime]::UtcNow -or $created -lt [DateTime]::UtcNow.AddDays(-$definitions.MediaCacheDays)) { continue }
if ($manifest.Version -notmatch $definitions.OfficeBuildPattern -or !$manifest.Files.Count) { throw 'Invalid cache manifest.' }
if ($Options.TargetOfficeVersion -and $manifest.Version -ne $Options.TargetOfficeVersion) { throw 'Cached Office build does not match the Windows 10 target.' }
$names = @('ODT', 'odt.exe') + @(Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams | ForEach-Object { $_.File })
foreach ($entry in $manifest.Files) {
if ([IO.Path]::IsPathRooted($entry.Path) -or $entry.Path -match '(^|[\\/])\.\.([\\/]|$)' -or ($entry.Path -split '[\\/]')[0] -notin $names) { throw 'Invalid cached file path.' }
$path = Join-Path $candidate.FullName $entry.Path
Assert-OfficeManagedPath $candidate.FullName $path
$file = Get-Item -LiteralPath $path -ErrorAction Stop
if ($file.PSIsContainer -or $file.Length -ne $entry.Length) { throw "Cached file is incomplete: $path" }
}
# Keep publisher checks on executable installers; do not hash the Office payload.
foreach ($name in @('odt.exe', 'ODT\setup.exe') + @(Get-OfficeCompanionDownloads -InstallTeams $Options.InstallTeams | ForEach-Object { $_.File })) {
Assert-OfficeMicrosoftSignature (Join-Path $candidate.FullName $name)
}
$actualFiles = @(foreach ($name in $names) { Get-OfficeManagedFiles $root (Join-Path $candidate.FullName $name) })
$actualPaths = @($actualFiles | ForEach-Object { $_.FullName.Substring($candidate.FullName.Length + 1) } | Sort-Object -Unique)
$expectedPaths = @($manifest.Files.Path | Sort-Object -Unique)
if ($actualFiles.Count -ne $manifest.Files.Count -or (Compare-Object $actualPaths $expectedPaths)) { throw 'Cached file inventory changed.' }
} catch {
$null = Write-Output "Ignoring unusable Office cache in $($candidate.FullName): $($_.Exception.Message)"
continue
}
# Transfer rather than duplicate several GB. Each deployment still has a new ID,
# so old per-user completion markers cannot suppress a new cleanup request.
foreach ($name in $names) {
$source = Join-Path $candidate.FullName $name; $destination = Join-Path $Workspace $name
Assert-OfficeManagedPath $root $source; Assert-OfficeManagedPath $root $destination
if (Test-Path -LiteralPath $destination) { throw "Cache destination already exists: $destination" }
Move-Item -LiteralPath $source -Destination $destination -ErrorAction Stop
}
Remove-OfficeManagedItem $root $manifestPath
$null = Write-Output "Reusing verified Office $($manifest.Version) media from $($candidate.FullName)."
return $manifest
} }
} }
function Assert-OfficeMicrosoftSignature { function Assert-OfficeMicrosoftSignature {
param([string]$Path) param([string]$Path)
$signature = Get-AuthenticodeSignature -LiteralPath $Path -ErrorAction Stop $signature = Get-AuthenticodeSignature -LiteralPath $Path -ErrorAction Stop
@@ -493,7 +553,7 @@ function Invoke-OfficeProcess {
} }
} }
function Write-OfficeSetupDiagnostics { function Get-OfficeSetupLogFiles {
param( param(
[DateTime]$SinceUtc, [DateTime]$SinceUtc,
[string[]]$SearchRoots = @([IO.Path]::GetTempPath(), "$env:WINDIR\Temp", "$env:WINDIR\SystemTemp") [string[]]$SearchRoots = @([IO.Path]::GetTempPath(), "$env:WINDIR\Temp", "$env:WINDIR\SystemTemp")
@@ -510,7 +570,16 @@ function Write-OfficeSetupDiagnostics {
} }
} catch { $null = Write-Output "Could not search native Office logs in ${root}: $($_.Exception.Message)" } } catch { $null = Write-Output "Could not search native Office logs in ${root}: $($_.Exception.Message)" }
}) })
$files = @($files | Sort-Object FullName -Unique | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First $definitions.SetupDiagnosticFileLimit) $files | Sort-Object FullName -Unique | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First $definitions.SetupDiagnosticFileLimit
}
function Write-OfficeSetupDiagnostics {
param(
[DateTime]$SinceUtc,
[string[]]$SearchRoots = @([IO.Path]::GetTempPath(), "$env:WINDIR\Temp", "$env:WINDIR\SystemTemp")
)
$definitions = Get-OfficeDeploymentDefinitions
$files = @(Get-OfficeSetupLogFiles -SinceUtc $SinceUtc -SearchRoots $SearchRoots)
if (!$files.Count) { if (!$files.Count) {
$null = Write-Output "No recent nonempty native Office logs found in: $($SearchRoots -join '; '). Empty ODT stdout/stderr files do not contain the underlying setup error." $null = Write-Output "No recent nonempty native Office logs found in: $($SearchRoots -join '; '). Empty ODT stdout/stderr files do not contain the underlying setup error."
return return
@@ -593,34 +662,14 @@ function Initialize-OfficeMedia {
param($Options, [string]$Workspace) param($Options, [string]$Workspace)
$definitions = Get-OfficeDeploymentDefinitions $definitions = Get-OfficeDeploymentDefinitions
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$Options.TargetOfficeVersion = '' if ($Options.OfficeFeatureRelease -and !$Options.TargetOfficeVersion) { Resolve-OfficeTargetVersion $Options $Workspace }
if ($Options.OfficeFeatureRelease) { Assert-OfficeDiskSpace -Workspace $Workspace -DownloadingMedia
$historyPath = Join-Path $Workspace 'office-release-history.html' # Download only in the install workflow; no persistent cache or cross-run reuse.
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.
$helper = Join-Path $Workspace 'Office-UserCleanup.ps1' $helper = Join-Path $Workspace 'Office-UserCleanup.ps1'
Save-OfficeDownload "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1" $helper Save-OfficeDownload "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1" $helper
$tokens = $null; $errors = $null $tokens = $null; $errors = $null
$null = [Management.Automation.Language.Parser]::ParseFile($helper, [ref]$tokens, [ref]$errors) $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.' } 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' $pagePath = Join-Path $Workspace 'odt-download-page.html'
Save-OfficeDownload $definitions.OdtPage $pagePath -TimeoutSeconds $definitions.OdtPageTimeoutSeconds Save-OfficeDownload $definitions.OdtPage $pagePath -TimeoutSeconds $definitions.OdtPageTimeoutSeconds
$url = Get-OfficeOdtDownloadUrl (Get-Content -LiteralPath $pagePath -Raw -ErrorAction Stop) $url = Get-OfficeOdtDownloadUrl (Get-Content -LiteralPath $pagePath -Raw -ErrorAction Stop)
@@ -636,6 +685,8 @@ function Initialize-OfficeMedia {
$removal = New-OfficeRemovalConfiguration $Options; $removal.Save($removalPath) $removal = New-OfficeRemovalConfiguration $Options; $removal.Save($removalPath)
$configPath = Join-Path $Workspace 'install.xml' $configPath = Join-Path $Workspace 'install.xml'
$config = New-OfficeConfiguration $Options $odtFolder $Options.TargetOfficeVersion; $config.Save($configPath) $config = New-OfficeConfiguration $Options $odtFolder $Options.TargetOfficeVersion; $config.Save($configPath)
$null = Write-Output "Office removal configuration: $($removal.OuterXml)"
$null = Write-Output "Office installation configuration: $($config.OuterXml)"
$null = Write-Output 'Downloading Office installation files before removing installed apps.' $null = Write-Output 'Downloading Office installation files before removing installed apps.'
for ($attempt = 1; $attempt -le $definitions.DownloadAttempts; $attempt++) { for ($attempt = 1; $attempt -le $definitions.DownloadAttempts; $attempt++) {
$prefix = if ($attempt -eq 1) { 'office-download' } else { "office-download.retry-$attempt" } $prefix = if ($attempt -eq 1) { 'office-download' } else { "office-download.retry-$attempt" }
@@ -653,8 +704,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" } 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 $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 } $media = [pscustomobject]@{ Setup = $setup; RemovalConfig = $removalPath; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions }
Save-OfficeMediaCache $Options $media $Workspace
$media $media
} }
@@ -795,27 +845,304 @@ function Get-OfficeSuiteInventory {
} }
} }
function Get-OfficeClickToRunState {
# Servicing metadata is diagnostic evidence, not installed-product inventory.
# A service can survive removal, and successful installs retain source URLs.
$root = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun'
$present = Test-Path -LiteralPath $root -ErrorAction Stop
$sources = @(); $working = @()
if ($present) {
$keys = @((Get-Item -LiteralPath $root -ErrorAction Stop)) + @(Get-ChildItem -LiteralPath $root -Recurse -ErrorAction Stop)
foreach ($key in $keys) {
$values = Get-ItemProperty -LiteralPath $key.PSPath -ErrorAction Stop
foreach ($property in $values.PSObject.Properties) {
if ($property.Name -like 'PS*') { continue }
foreach ($value in @($property.Value)) {
if ($value -isnot [string] -or !$value.Trim()) { continue }
if ($value -match '(?i)EmberkomOfficeDeployment[\\/]') { $sources += "$($key.Name) : $($property.Name) = $value" }
if ($property.Name -match '^WorkingConfig(uration)?$' -and $value.Trim('{}') -ne '00000000-0000-0000-0000-000000000000') { $working += $value }
}
}
}
}
$service = Get-Service -Name ClickToRunSvc -ErrorAction SilentlyContinue
[pscustomobject]@{ Present=($present -or $null -ne $service); SourceReferences=$sources; WorkingConfiguration=$working }
}
function Assert-OfficeRemovalComplete {
param([string]$Workspace)
$idle = Wait-OfficeResult { !(Test-OfficeStagingInUse $Workspace @(Get-CimInstance Win32_Process -ErrorAction Stop)) } 'Office installation/removal workers to finish before replacement'
if (!$idle) { throw 'Office installation/removal workers are still running. Installation stopped to avoid overlapping operations.' }
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 })
if ($remaining.Count) { throw "Click-to-Run products remain before replacement: $($remaining.DisplayName -join '; '). Installation stopped." }
$state = Get-OfficeClickToRunState
$null = Write-Output "Office removal verified: no registered Click-to-Run products or active installer workers. Diagnostic metadata: $($state.SourceReferences.Count) staging references; working configuration: $($state.WorkingConfiguration -join ', '). Metadata alone does not require removal; ODT will configure this run's fresh media."
}
function Get-OfficeRemovalCorruptionEvidence {
param([DateTime]$SinceUtc)
$finishedUtc = [DateTime]::UtcNow
foreach ($file in @(Get-OfficeSetupLogFiles -SinceUtc $SinceUtc)) {
try {
foreach ($line in @(Get-Content -LiteralPath $file.FullName -Tail (Get-OfficeDeploymentDefinitions).SetupDiagnosticTailLines -ErrorAction Stop)) {
# An exit code alone cannot distinguish corrupt state from network,
# source or policy problems. Require a removal-specific native error
# timestamped during THIS attempt, not an old error in a live log.
if ($line -notmatch '(?i)InvalidDirectory' -or $line -notmatch '(?i)REMOVEINSTALLATION') { continue }
if ($line -notmatch '^\s*(\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2}:\d{2}\.\d{3})\s') { continue }
$stamp = [DateTime]::MinValue
if (![DateTime]::TryParseExact($Matches[1], 'M/d/yyyy H:mm:ss.fff', [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::AssumeLocal, [ref]$stamp)) { continue }
if ($stamp.ToUniversalTime() -lt $SinceUtc.AddSeconds(-1) -or $stamp.ToUniversalTime() -gt $finishedUtc) { continue }
return [pscustomobject]@{ Path=$file.FullName; Detail=$line }
}
} catch { $null = Write-Output "Could not classify Office removal failure from $($file.FullName): $($_.Exception.Message)" }
}
}
function Initialize-OfficeScrubMedia {
param([string]$Workspace)
$definitions = Get-OfficeDeploymentDefinitions
$archivePath = Join-Path $Workspace 'GetHelp.zip'
$folder = Join-Path $Workspace 'GetHelp'
if ((Test-Path -LiteralPath $archivePath) -or (Test-Path -LiteralPath $folder)) { throw 'Scrub media already exists in this run; refusing to reuse it or repeat recovery.' }
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Save-OfficeDownload $definitions.GetHelpUrl $archivePath
# Validate every entry before extraction, including on older PS 5.1 archive modules.
Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem
$archive = [IO.Compression.ZipFile]::OpenRead($archivePath)
try {
foreach ($entry in $archive.Entries) {
if (!$entry.FullName -or $entry.FullName.Contains(':')) { throw 'Unexpected path in Get Help archive.' }
Assert-OfficeManagedPath $folder ([IO.Path]::Combine($folder, $entry.FullName))
}
} finally { $archive.Dispose() }
# Tools.ps1 overrides Expand-Archive with a Path-only wrapper.
Microsoft.PowerShell.Archive\Expand-Archive -LiteralPath $archivePath -DestinationPath $folder -ErrorAction Stop
$files = @(Get-OfficeManagedFiles $Workspace $folder)
$executables = @($files | Where-Object { $_.Name -eq $definitions.GetHelpExecutable })
if ($executables.Count -ne 1) { throw "Microsoft download did not contain exactly one $($definitions.GetHelpExecutable)." }
Assert-OfficeMicrosoftSignature $executables[0].FullName
$executables[0].FullName
}
function Read-OfficeScrubOutput {
param([string]$LogPrefix)
$definitions = Get-OfficeDeploymentDefinitions
$output = @()
foreach ($stream in @('stdout', 'stderr')) {
$path = "$LogPrefix.$stream.log"
$file = Get-Item -LiteralPath $path -ErrorAction Stop
[string]$content = Get-Content -LiteralPath $path -Raw -ErrorAction Stop
$null = Write-Output "Get Help ${stream}: $($file.Length) bytes in $path"
if ([string]::IsNullOrWhiteSpace($content)) { $null = Write-Output "Get Help ${stream}: no text captured." }
else {
$lines = @($content -split '\r?\n' | Where-Object { ![string]::IsNullOrWhiteSpace($_) })
if ($lines.Count -gt $definitions.ScrubDiagnosticLineLimit) {
# Usage failures put the reason first and examples last. Preserve both.
$headCount = [int][Math]::Floor($definitions.ScrubDiagnosticLineLimit / 2)
$lines = @($lines | Select-Object -First $headCount) + @('[middle output omitted; see full stream log]') + @($lines | Select-Object -Last ($definitions.ScrubDiagnosticLineLimit - $headCount))
}
foreach ($line in $lines) {
if ($line.Length -gt $definitions.ScrubDiagnosticLineCharacters) { $line = $line.Substring(0, $definitions.ScrubDiagnosticLineCharacters) + ' [truncated; see full stream log]' }
$null = Write-Output "Get Help ${stream} detail: $line"
}
}
$output += $content
}
$output -join "`n"
}
function Get-OfficeScrubArguments {
param([int]$ExitCode, [string]$HelpText)
$definitions = Get-OfficeDeploymentDefinitions
if ($ExitCode -ne 0 -or $HelpText -match $definitions.ScrubFailurePattern -or $HelpText -notmatch $definitions.ScrubHelpPattern) {
throw "Could not validate the downloaded Get Help command syntax (exit $ExitCode). Scrub was not launched. Check gethelp-usage logs."
}
if ($HelpText -match $definitions.ScrubVersionSwitchPattern) { return "$($definitions.ScrubArguments) $($definitions.ScrubAllVersionsArgument)" }
return $definitions.ScrubArguments
}
function Get-OfficeScrubWorkers {
$definitions = Get-OfficeDeploymentDefinitions
$filter = ($definitions.ScrubWorkerNames | ForEach-Object { "Name='$_'" }) -join ' OR '
Get-CimInstance Win32_Process -Filter $filter -ErrorAction Stop | Where-Object {
$_.ProcessId -ne $PID -and
!($_.Name -eq 'msiexec.exe' -and $_.CommandLine -match '(?i)\s/(V|Embedding)(?:\s|$)') -and
!($_.Name -eq 'OfficeClickToRun.exe' -and $_.CommandLine -match '(?i)\s/(service|user)\s*$')
}
}
function Open-OfficeScrubWorkerHandle {
param($Worker)
# Hold a real handle before the process exits. Looking up a departed PID later
# loses its exit code and can accidentally refer to a reused PID.
$process = $null
try {
$process = [Diagnostics.Process]::GetProcessById([int]$Worker.ProcessId)
$null = $process.Handle
if (!$Worker.CreationDate -or [Math]::Abs(($process.StartTime.ToUniversalTime() - ([datetime]$Worker.CreationDate).ToUniversalTime()).TotalMilliseconds) -gt 1) { throw 'Process identity changed.' }
return $process
} catch {
if ($process) { $process.Dispose() }
throw "Could not monitor scrub worker PID $($Worker.ProcessId): $($_.Exception.Message) Installation stopped; worker disappearance is not proof of successful removal."
}
}
function Get-OfficeScrubReportRoots {
param($Worker)
try {
$owner = Invoke-CimMethod -InputObject $Worker -MethodName GetOwnerSid -ErrorAction Stop
if ($owner.ReturnValue -ne 0 -or !$owner.Sid) { throw 'Worker owner SID is unavailable.' }
if ($owner.Sid -eq 'S-1-5-18') {
"$env:WINDIR\System32\config\systemprofile\AppData\Local\DAFs"
"$env:WINDIR\SysWOW64\config\systemprofile\AppData\Local\DAFs"
} else {
$profile = Get-ItemPropertyValue -LiteralPath "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$($owner.Sid)" -Name ProfileImagePath -ErrorAction Stop
Join-Path ([Environment]::ExpandEnvironmentVariables($profile)) 'AppData\Local\DAFs'
}
} catch { $null = Write-Output "Could not locate diagnostic reports for scrub worker PID $($Worker.ProcessId): $($_.Exception.Message). Process and product verification remain required." }
}
function Read-OfficeScrubWorkerReport {
param($Worker, [string[]]$Roots)
foreach ($root in $Roots) {
try {
if (!(Test-Path -LiteralPath $root -ErrorAction Stop)) { continue }
foreach ($file in @(Get-ChildItem -LiteralPath $root -Filter 'cse.amplify.diagaction.gethelp.officeuninstallalda_*.log' -File -ErrorAction Stop)) {
# Only fresh reports in this worker's account. Never apply an older
# scrub's failure to the current run or use a report to kill a worker.
if ($file.CreationTimeUtc -lt ([datetime]$Worker.CreationDate).ToUniversalTime() -or $file.LastWriteTimeUtc -lt ([datetime]$Worker.CreationDate).ToUniversalTime() -or $file.Length -gt 1MB) { continue }
$text = Get-Content -LiteralPath $file.FullName -Raw -ErrorAction Stop
if ($text -notmatch '(?s)\bReport:\s*(\{.*\})\s*$') { continue }
try { $report = $Matches[1] | ConvertFrom-Json -ErrorAction Stop } catch { continue } # It may still be being written.
if ($report.TroubleshooterName -ne 'GH_OfficeUninstallALDA' -or !$report.ExecutionResult) { continue }
[pscustomobject]@{ Path=$file.FullName; Result=$report.ExecutionResult; Detail=$report.ExecutionResultDetails }
}
} catch { $null = Write-Output "Could not read scrub reports in ${root}: $($_.Exception.Message)." }
}
}
function Wait-OfficeScrubRemoval {
param([object[]]$ExistingWorkers)
$definitions = Get-OfficeDeploymentDefinitions
$baseline = @{}; $handles = @{}; $quietChecks = 0; $lastState = $null; $observedWorker = $false
foreach ($worker in $ExistingWorkers) { $baseline["$($worker.ProcessId)|$(([datetime]$worker.CreationDate).ToUniversalTime().Ticks)"] = $true }
$null = Write-Output "Get Help started background removal. Waiting up to $([int](($definitions.ScrubBackgroundCheckAttempts - 1) * $definitions.ScrubBackgroundCheckSeconds / 60)) minutes for workers and Office registrations to clear, followed by a $([int](($definitions.ScrubBackgroundQuietChecks - 1) * $definitions.ScrubBackgroundCheckSeconds))-second quiet interval."
$null = Write-Output "Leave the Microsoft cleanup window open until it reports completion. If it says 'Press any key to exit', dismiss that completed prompt to let verification continue. Closing it during removal can fail deployment."
try {
for ($attempt = 1; $attempt -le $definitions.ScrubBackgroundCheckAttempts; $attempt++) {
$workers = @(Get-OfficeScrubWorkers | Where-Object {
!$baseline.ContainsKey("$($_.ProcessId)|$(([datetime]$_.CreationDate).ToUniversalTime().Ticks)") -or $_.CommandLine -match '(?i)(OffScrub|OfficeScrub|OfficeUninstall|GetHelpElevated)'
})
foreach ($worker in $workers) {
# Track a completion code for identified Microsoft script workers.
# Newly started unrelated consoles still delay the quiet interval,
# as in the previous implementation, but cannot prove scrub ran.
if ($worker.CommandLine -notmatch '(?i)(OffScrub|OfficeScrub|OfficeUninstall|GetHelpElevated)') { continue }
$identity = "$($worker.ProcessId)|$(([datetime]$worker.CreationDate).ToUniversalTime().Ticks)"
if (!$handles.ContainsKey($identity)) {
$handles[$identity] = [pscustomobject]@{ Process=(Open-OfficeScrubWorkerHandle $worker); Checked=$false; Id=$worker.ProcessId; Worker=$worker; ReportRoots=@(Get-OfficeScrubReportRoots $worker) }
$observedWorker = $true
$null = Write-Output "Monitoring scrub worker $($worker.Name), PID $($worker.ProcessId), created $($worker.CreationDate). Command: $($worker.CommandLine)"
}
}
$liveHandles = 0
foreach ($watch in $handles.Values) {
foreach ($report in @(Read-OfficeScrubWorkerReport $watch.Worker $watch.ReportRoots)) {
if ($report.Result -eq 'Failed') { throw "Get Help worker reported failure: $($report.Detail) Report: $($report.Path). Installation stopped. Its console may now be waiting at the final keypress prompt; that process lifetime is not ongoing cleanup." }
}
if ($watch.Checked) { continue }
if (!$watch.Process.HasExited) { $liveHandles++; continue }
$exitCode = $watch.Process.ExitCode
if ($null -eq $exitCode -or $exitCode -notin @(0, 3010)) { throw "Scrub worker PID $($watch.Id) exited unsuccessfully (exit $exitCode); it may have failed or been closed. Installation stopped." }
$watch.Checked = $true
$null = Write-Output "Scrub worker PID $($watch.Id) exited $exitCode. Removal still requires independent verification."
}
$remaining = @(Get-OfficeSuiteInventory)
$status = "Office registrations remaining: $($remaining.Count) [$(($remaining.DisplayName | Sort-Object) -join '; ')]; workers: $(($workers | ForEach-Object { "$($_.Name) PID $($_.ProcessId)" } | Sort-Object) -join '; '); live monitored workers: $liveHandles; observed scrub worker: $observedWorker"
if ($status -ne $lastState -or $attempt % 6 -eq 0) { $null = Write-Output $status; $lastState = $status }
if ($observedWorker -and !$remaining.Count -and !$workers.Count -and !$liveHandles) { $quietChecks++ } else { $quietChecks = 0 }
if ($quietChecks -ge $definitions.ScrubBackgroundQuietChecks) { return }
if ($attempt -lt $definitions.ScrubBackgroundCheckAttempts) { Start-Sleep -Seconds $definitions.ScrubBackgroundCheckSeconds }
}
throw "Get Help background removal did not finish verification within the allowed time. $status. Installation has not started and this deployment will not resume automatically. A live worker alone cannot distinguish active removal from the final keypress prompt, which Microsoft displays after success OR failure. Inspect its final console output or diagnostic report before dismissing a completed prompt."
} finally {
foreach ($watch in $handles.Values) { $watch.Process.Dispose() }
}
}
function Invoke-OfficeScrubRecovery {
param($Media, [string]$Workspace, [string]$Reason)
if ($Media.ScrubAttempted) { throw 'Office scrub recovery was already attempted. Installation stopped; no repeated scrub or install loop will run.' }
$Media | Add-Member -NotePropertyName ScrubAttempted -NotePropertyValue $true -Force
$Media | Add-Member -NotePropertyName ScrubReason -NotePropertyValue $Reason -Force
$null = Write-Output "Office scrub recovery selected: $Reason"
$null = Write-Output 'Running one Microsoft Get Help OfficeScrubScenario attempt for detected Office installations. All Office registrations must be gone before replacement installation. Get Help may display a child window despite the hidden launch.'
$scrubber = Initialize-OfficeScrubMedia $Workspace
$helpPrefix = Join-Path $Workspace 'gethelp-usage'
$helpCode = Invoke-OfficeProcess $scrubber '-?' $helpPrefix
$arguments = Get-OfficeScrubArguments $helpCode (Read-OfficeScrubOutput $helpPrefix)
$null = Write-Output "Validated Get Help command: $arguments"
$prefix = Join-Path $Workspace 'office-scrub'
$existingWorkers = @(Get-OfficeScrubWorkers)
$blocking = @(Get-OfficeBlockingProcesses $Workspace $existingWorkers)
if ($blocking.Count) { throw "Cannot launch scrub while another installation/removal worker is running: $(($blocking | ForEach-Object { "$($_.Name) PID $($_.ProcessId)" }) -join '; '). Installation stopped to avoid overlapping cleanup." }
$code = Invoke-OfficeProcess $scrubber $arguments $prefix
$output = Read-OfficeScrubOutput $prefix
if ($output -match '(?im)^\s*(Error:\s*)?Invalid command line arguments\b|^\s*Usage:\s*GetHelpCmd\.exe\b') {
throw "Get Help rejected its command line and printed usage (process $code). No scrub success was reported. Arguments: $arguments. See Get Help stdout/stderr details in the management log and $prefix.stdout.log."
}
$definitions = Get-OfficeDeploymentDefinitions
$results = @([regex]::Matches($output, '(?m)^\s*(\d{2}):') | ForEach-Object { $_.Groups[1].Value })
$null = Write-Output "Get Help scrub result: process $code; scenario results $($results -join ', '). Logs: $prefix"
# 66/68 mean Office was not found, not a verified repair of damaged state.
if ($code -notin @(0, 3010) -or $output -match $definitions.ScrubFailurePattern -or @($results | Where-Object { $_ -ne '00' }).Count -or (!$results.Count -and $output -notmatch $definitions.ScrubTextSuccessPattern)) { throw "Get Help scrub failed or returned an unverified result (process $code; scenarios $($results -join ', ')). Installation stopped. See $prefix.stdout.log and $prefix.stderr.log." }
if ($output -match $definitions.ScrubBackgroundPattern) { Wait-OfficeScrubRemoval $existingWorkers }
$idle = Wait-OfficeResult { !(Test-OfficeStagingInUse $Workspace @(Get-CimInstance Win32_Process -ErrorAction Stop)) } 'Office scrub child processes to finish'
if (!$idle) { throw 'Office scrub processes are still running. Installation stopped to avoid concurrent removal and installation.' }
$removed = Wait-OfficeResult { @(Get-OfficeSuiteInventory).Count -eq 0 } 'all Office registrations to disappear after Get Help scrub'
if (!$removed) { throw "Office remains after Get Help scrub: $((Get-OfficeSuiteInventory).DisplayName -join '; '). Installation stopped." }
Assert-OfficeRemovalComplete $Workspace
$null = Write-Output 'Office scrub recovery verified. Reporting restart required; DeferReboot controls whether installation can finish before that restart.'
return 3010
}
function Remove-OfficeSuite { function Remove-OfficeSuite {
param($Media, [string]$Workspace) param($Media, [string]$Workspace)
# Get Help can create an interactive elevated child despite a hidden SYSTEM parent. # ODT is the normal path. A single Get Help scrub is reserved for evidence of
# Never fall back to it automatically. ODT owns the supported silent removal path. # broken product removal, before replacement installation begins.
$existing = @(Get-OfficeSuiteInventory) $existing = @(Get-OfficeSuiteInventory)
$msi = @($existing | Where-Object { $_.WindowsInstaller -eq 1 }) $msi = @($existing | Where-Object { $_.WindowsInstaller -eq 1 })
if ($msi.Count) { $null = Write-Output "MSI Office will be removed by ODT RemoveMSI before it installs the replacement suite: $($msi.DisplayName -join '; ')." } if ($msi.Count) { $null = Write-Output "MSI Office will be removed by ODT RemoveMSI before it installs the replacement suite: $($msi.DisplayName -join '; ')." }
if (!@($existing | Where-Object { $_.WindowsInstaller -ne 1 }).Count) { if (!@($existing | Where-Object { $_.WindowsInstaller -ne 1 }).Count) {
$null = Write-Output 'No non-MSI Office products detected; skipping the separate ODT removal pass.' $null = Write-Output 'No registered Click-to-Run products detected; skipping ODT removal and scrub. A remaining ClickToRunSvc or servicing key is not an installed Office product. MSI products remain assigned to RemoveMSI during installation.'
return 0 return 0
} }
if (!$Media.RemovalConfig -or !(Test-Path -LiteralPath $Media.RemovalConfig -PathType Leaf)) { throw 'The staged silent Office removal configuration is missing.' } if (!$Media.RemovalConfig -or !(Test-Path -LiteralPath $Media.RemovalConfig -PathType Leaf)) { throw 'The staged silent Office removal configuration is missing.' }
$null = Write-Output 'Silently removing Click-to-Run Office, including Visio and Project, with ODT.' $null = Write-Output "Silently removing registered Click-to-Run products with ODT: $(($existing | Where-Object { $_.WindowsInstaller -ne 1 }).DisplayName -join '; ')."
$startedUtc = [DateTime]::UtcNow
$code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.RemovalConfig)`"" (Join-Path $Workspace 'office-remove') $code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.RemovalConfig)`"" (Join-Path $Workspace 'office-remove')
$manual = "No interactive scrubber was launched. Arrange an attended manual scrub if needed: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)" if ($code -notin @(0, 3010)) {
if ($code -notin @(0, 3010)) { throw "Silent ODT Office removal failed (exit $code). See logs in $Workspace. $manual" } if ($code -in (Get-OfficeDeploymentDefinitions).ScrubRecoveryExitCodes) {
$evidence = Get-OfficeRemovalCorruptionEvidence -SinceUtc $startedUtc
if ($evidence) {
$null = Write-Output "Office scrub trigger evidence: $($evidence.Path) : $($evidence.Detail)"
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 })
if (!$remaining.Count) {
Assert-OfficeRemovalComplete $Workspace
$null = Write-Output "ODT removal exited $code, but no Click-to-Run products or active workers remain. Skipping a scrub with no product to remove; reporting restart required before continuing according to DeferReboot."
return 3010
}
return Invoke-OfficeScrubRecovery $Media $Workspace "ODT removal exit $code with a current REMOVEINSTALLATION InvalidDirectory error."
}
}
throw "Silent ODT Office removal failed (exit $code). No confirmed removal-corruption evidence was found; automatic scrub was not selected. See logs in $Workspace. Manual troubleshooting: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)"
}
if ($code -eq 3010) { return 3010 } if ($code -eq 3010) { return 3010 }
$removed = Wait-OfficeResult { @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 }).Count -eq 0 } 'Click-to-Run Office removal registration' $removed = Wait-OfficeResult { @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 }).Count -eq 0 } 'Click-to-Run Office removal registration'
if (!$removed) { if (!$removed) {
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 }) $remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 })
throw "Office remains after silent ODT removal: $($remaining.DisplayName -join '; '). Installation stopped. $manual" return Invoke-OfficeScrubRecovery $Media $Workspace "Office remains after successful ODT removal: $($remaining.DisplayName -join '; ')."
} }
return 0 return 0
} }
@@ -1011,6 +1338,25 @@ function Clear-OfficeProfileIdentity {
} }
} }
function New-OfficeUserCleanupCommand {
param([ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId)
$definitions = Get-OfficeDeploymentDefinitions
$uri = "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1".Replace("'", "''")
$version = $definitions.HelperVersion.Replace("'", "''")
$command = @'
$ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
try {
$client = New-Object Net.WebClient
try { $source = $client.DownloadString('__URI__') } finally { $client.Dispose() }
if (!$source.Contains('__VERSION__')) { throw 'Office user cleanup helper version does not match its deployment.' }
& ([scriptblock]::Create($source)) -DeploymentId '__ID__'
} catch { Write-Error $_ -ErrorAction Continue; exit 1 }
'@
$command = $command.Replace('__URI__', $uri).Replace('__VERSION__', $version).Replace('__ID__', $DeploymentId)
[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
}
function Start-OfficeUserCleanup { function Start-OfficeUserCleanup {
param([object[]]$Profiles, $Media, [string]$Workspace) param([object[]]$Profiles, $Media, [string]$Workspace)
$definitions = Get-OfficeDeploymentDefinitions $definitions = Get-OfficeDeploymentDefinitions
@@ -1018,7 +1364,8 @@ function Start-OfficeUserCleanup {
foreach ($profile in $Profiles) { foreach ($profile in $Profiles) {
$name = "Emberkom-OfficeCleanup-$deploymentId-$($profile.SID)" $name = "Emberkom-OfficeCleanup-$deploymentId-$($profile.SID)"
try { try {
$action = New-ScheduledTaskAction -Execute "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$($Media.Helper)`" -DeploymentId $deploymentId" -ErrorAction Stop $command = New-OfficeUserCleanupCommand $deploymentId
$action = New-ScheduledTaskAction -Execute "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand $command" -ErrorAction Stop
$principal = New-ScheduledTaskPrincipal -UserId $profile.SID -LogonType Interactive -RunLevel Limited -ErrorAction Stop $principal = New-ScheduledTaskPrincipal -UserId $profile.SID -LogonType Interactive -RunLevel Limited -ErrorAction Stop
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $profile.SID -ErrorAction Stop $trigger = New-ScheduledTaskTrigger -AtLogOn -User $profile.SID -ErrorAction Stop
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes $definitions.UserCleanupTaskMinutes) -MultipleInstances IgnoreNew -ErrorAction Stop $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes $definitions.UserCleanupTaskMinutes) -MultipleInstances IgnoreNew -ErrorAction Stop
@@ -1060,11 +1407,11 @@ function Install-OfficeMedia {
param($Options, $Media, [string]$Workspace) param($Options, $Media, [string]$Workspace)
$msi = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 }) $msi = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 })
$code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.Config)`"" (Join-Path $Workspace 'office-install') $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 automatic scrub is attempted after replacement installation begins." }
$msiRemoved = Wait-OfficeResult { @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 }).Count -eq 0 } 'legacy MSI Office removal by ODT' $msiRemoved = Wait-OfficeResult { @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 }).Count -eq 0 } 'legacy MSI Office removal by ODT'
if (!$msiRemoved) { if (!$msiRemoved) {
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 }) $remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 })
throw "MSI Office remains after ODT RemoveMSI: $($remaining.DisplayName -join '; '). Deployment is incomplete; the new suite may already be installed. No interactive scrubber was launched. Arrange an attended manual scrub if needed: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)" throw "MSI Office remains after ODT RemoveMSI: $($remaining.DisplayName -join '; '). Deployment is incomplete; the new suite may already be installed. No automatic scrub is attempted after replacement installation begins. Arrange an attended manual scrub if needed: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)"
} }
$platform = if ($Options.OfficeArchitecture -eq '64') { 'x64' } else { 'x86' } $platform = if ($Options.OfficeArchitecture -eq '64') { 'x64' } else { 'x86' }
$verified = Wait-OfficeResult { $verified = Wait-OfficeResult {
@@ -1072,7 +1419,7 @@ function Install-OfficeMedia {
if (!(Test-Path -LiteralPath $key -ErrorAction Stop)) { return $false } if (!(Test-Path -LiteralPath $key -ErrorAction Stop)) { return $false }
$installed = Get-ItemProperty -LiteralPath $key -ErrorAction Stop $installed = Get-ItemProperty -LiteralPath $key -ErrorAction Stop
if ($Options.ProductId -notin ($installed.ProductReleaseIds -split ',') -or $installed.Platform -ne $platform -or $installed.VersionToReport -notmatch (Get-OfficeDeploymentDefinitions).OfficeBuildPattern) { return $false } if ($Options.ProductId -notin ($installed.ProductReleaseIds -split ',') -or $installed.Platform -ne $platform -or $installed.VersionToReport -notmatch (Get-OfficeDeploymentDefinitions).OfficeBuildPattern) { return $false }
# Unpinned ODT can install a newer build than the earlier validation download. # Unpinned ODT can install a newer build than this run's earlier download.
# Windows 10 must still match its explicitly selected compatible build. # Windows 10 must still match its explicitly selected compatible build.
if ($Options.TargetOfficeVersion) { if ($Options.TargetOfficeVersion) {
if ($installed.VersionToReport -ne $Options.TargetOfficeVersion) { return $false } if ($installed.VersionToReport -ne $Options.TargetOfficeVersion) { return $false }
@@ -1097,49 +1444,60 @@ function Invoke-OfficeDeployment {
Assert-OfficeDeploymentHost $Options Assert-OfficeDeploymentHost $Options
$mutex = New-Object Threading.Mutex($false, 'Global\EmberkomOfficeDeployment') $mutex = New-Object Threading.Mutex($false, 'Global\EmberkomOfficeDeployment')
$locked = $false $locked = $false
$workspace = $null; $userWorkspace = $null; $receipt = $null; $completed = $false
try { try {
try { $locked = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $locked = $true } try { $locked = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $locked = $true }
if (!$locked) { throw 'Another Emberkom Office deployment is running.' } if (!$locked) { throw 'Another Emberkom Office deployment is running.' }
$runningApps = @(Get-OfficeRunningApps | Select-Object -ExpandProperty ProcessName -Unique) $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." } 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)."
$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 }) $profiles = @(Get-CimInstance Win32_UserProfile -ErrorAction Stop | Where-Object { !$_.Special -and $_.LocalPath })
# Unavailable containers/roaming profiles must not silently disappear from the cleanup report. # Unavailable containers/roaming profiles must not silently disappear from the cleanup report.
foreach ($profile in $profiles) { 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." } 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 $stagingRoot = Join-Path ([IO.Path]::GetTempPath()) 'EmberkomOfficeDeployment'
# Also check cache hits: a successful download does not prove enough space $paths = @($stagingRoot, (Join-Path $env:ProgramData 'EmberkomOfficeDeployment'), $env:ProgramFiles, ${env:ProgramFiles(x86)})
# remains to expand Office and install the selected companion apps. $writablePaths = @($paths | Where-Object { $_ } | Select-Object -Unique | ForEach-Object { Assert-OfficeWritablePath $_ })
Assert-OfficeDiskSpace -Workspace $workspace
if ($Options.ValidateBeforeChanges) { if ($Options.ValidateBeforeChanges) {
Assert-OfficeDiskSpace -Workspace $stagingRoot -DownloadingMedia
$downloadChecks = @(Test-OfficeDownloadLinks $Options)
$existingOffice = @(Get-OfficeSuiteInventory | ForEach-Object { $_.DisplayName }) $existingOffice = @(Get-OfficeSuiteInventory | ForEach-Object { $_.DisplayName })
# This helper is refreshed on every run; validation does not need to retain it. $state = Get-OfficeClickToRunState
Remove-OfficeManagedItem $root $media.Helper $null = Write-Output 'Assessment passed. HTTP HEAD checks returned 200; no response bodies downloaded or deployment directory created. Exact ODT package and Office build resolution/signature verification occur only during deployment.'
$null = Write-Output 'Validation passed. Stopped before closing apps, uninstalling, clearing identities, registering user cleanup tasks, or installing.'
return [pscustomobject]@{ return [pscustomobject]@{
OfficeDeploymentStatus='ValidationPassed'; ExitCode=0; ValidateBeforeChanges=$true 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 UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams; OfficeRemovalMethod='SilentODT'; DeferReboot=$Options.DeferReboot
Workspace=$workspace; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps Workspace=$null; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps; MediaDownloaded=$false
CachedMediaReused=[bool]$media.CachedMediaReused; MediaCacheDays=(Get-OfficeDeploymentDefinitions).MediaCacheDays WritablePaths=$writablePaths; DownloadChecks=$downloadChecks; ClickToRunState=$state; OfficeFeatureRelease=$Options.OfficeFeatureRelease; MetadataResolved=$false
NextStep='Set ValidateBeforeChanges=false to deploy. Matching unexpired media is verified and reused; prerequisites are checked again.' ScrubRecoveryPolicy='One Get Help scrub for failed removal with registered Click-to-Run products remaining; deployment only. Servicing metadata alone does not trigger removal.'
NextStep='Set ValidateBeforeChanges=false to download, verify, deploy, and clean up installation media. Prerequisites are checked again.'
} }
} }
Clear-OfficePreviousDeploymentFiles
Assert-OfficeDiskSpace -Workspace $stagingRoot -DownloadingMedia
$workspace = New-OfficeWorkspace
$null = Write-Output "Temporary deployment workspace: $workspace"
# Keep the request in a diagnostic log; XML and options are never reused.
$Options | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $workspace 'deployment-options.log') -Encoding UTF8
Resolve-OfficeTargetVersion $Options $workspace
$media = Initialize-OfficeMedia $Options $workspace
Assert-OfficeDiskSpace -Workspace $workspace
Stop-OfficeDeploymentApps $Options Stop-OfficeDeploymentApps $Options
$reboot = Remove-OfficeCompanionApps $workspace $reboot = Remove-OfficeCompanionApps $workspace
if ($reboot -and !(Test-OfficeCanDeferRestart $Options 'Companions')) { if ($reboot -and !(Test-OfficeCanDeferRestart $Options 'Companions')) {
$null = Write-Output 'Companion app removal requires a restart. Restart and rerun; Office installation has not started.' $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 $removalCode = Remove-OfficeSuite $media $workspace
if ($removalCode -eq 3010 -and !(Test-OfficeCanDeferRestart $Options 'Office')) { 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.' $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; ScrubRecoveryAttempted=[bool]$media.ScrubAttempted; ScrubRecoveryReason=$media.ScrubReason }
return $receipt
} }
Assert-OfficeRemovalComplete $workspace
foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile } foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile }
$userWorkspace = $workspace $userWorkspace = $workspace
if ($profiles.Count) { $userWorkspace = New-OfficeUserWorkspace $media $workspace } if ($profiles.Count) { $userWorkspace = New-OfficeUserWorkspace $media $workspace }
@@ -1155,14 +1513,19 @@ function Invoke-OfficeDeployment {
$provisionedApps = if ($Options.InstallTeams) { 'Teams and new Outlook are' } else { 'New Outlook is' } $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 "$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.' $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 = @() $completed = $true
try { $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; ScrubRecoveryAttempted=[bool]$media.ScrubAttempted; ScrubRecoveryReason=$media.ScrubReason }
$cleanupWarnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace -PreviousRoot (Join-Path $env:ProgramData 'EmberkomOfficeDeployment') return $receipt
}
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) }
} finally { } 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 -and $receipt.ExitCode -eq 0) { $receipt.ExitCode = 2; $receipt.OfficeDeploymentStatus = 'InstalledWithArtifactCleanupPending' }
}
if ($cleanupWarnings.Count) { $null = Write-Output 'Some deployment artifacts could not be removed safely. Stop surviving installers before rerunning; the next deployment must clean prior artifacts before downloading fresh media.' }
}
if ($locked) { $mutex.ReleaseMutex() } if ($locked) { $mutex.ReleaseMutex() }
$mutex.Dispose() $mutex.Dispose()
} }
@@ -1215,9 +1578,9 @@ function Invoke-OfficeDeploymentEntry {
} }
$null = Write-Output "Office deployment host: Windows PowerShell $($PSVersionTable.PSVersion), $([IntPtr]::Size * 8)-bit." $null = Write-Output "Office deployment host: Windows PowerShell $($PSVersionTable.PSVersion), $([IntPtr]::Size * 8)-bit."
if ($options.ValidateBeforeChanges) { 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, writable paths and HTTP HEAD 200 responses. No metadata or payload downloads, deployment directory, artifact cleanup, app shutdown, or installation will run.'
} else { } else {
Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: validating and staging media, then silently removing Office with ODT and reinstalling Office and the selected companion apps.' Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: clearing prior artifacts, downloading fresh media, then silently removing Office with ODT and installing the selected apps. Download workspaces retain only logs after cleanup.'
} }
Microsoft.PowerShell.Utility\Write-Output "Diagnostic log: $Global:LogFile" Microsoft.PowerShell.Utility\Write-Output "Diagnostic log: $Global:LogFile"
$results = @(Invoke-OfficeDeployment -Options $options) $results = @(Invoke-OfficeDeployment -Options $options)
+39 -1
View File
@@ -14,15 +14,36 @@ You can then run any of the scripts using the Run-Script function:
If you're using an RMM tool, the scripts in the /rmm directory are all that's needed to hook the main script in this directory. If you're using an RMM tool, the scripts in the /rmm directory are all that's needed to hook the main script in this directory.
For QuickBooks image-backup preparation, use [Stop-QuickBooksDesktop.ps1](Stop-QuickBooksDesktop.ps1)
and [Start-QuickBooksDesktop.ps1](Start-QuickBooksDesktop.ps1). The permanent
[stop shim](rmm/Stop-QuickBooksDesktop.ps1) defines the host's exact company-file
share names as a semicolon-separated string and pairs with the
[start shim](rmm/Start-QuickBooksDesktop.ps1). See [deployment, exit codes, and
recovery](docs/QuickBooks-Backup.md) before scheduling: desktop, database-service,
share-isolation, or open-handle failures prevent backup; post restores the
recorded services and share access. Each shim downloads its matching repository
script, `Tools.ps1`, and the shared QuickBooks routines live on every run. Only
the two shims need deployment; recovery state persists locally and no code is cached.
For DSA collection, paste [rmm/Get-DSAManifest.ps1](rmm/Get-DSAManifest.ps1) into the RMM caller, preserving its configured platform variables. This caller selects TLS 1.2 before downloading, stops on bootstrap failure, and dot-sources the downloaded tools in the caller's scope. Updating the repository alone will not change an existing RMM caller. For DSA collection, paste [rmm/Get-DSAManifest.ps1](rmm/Get-DSAManifest.ps1) into the RMM caller, preserving its configured platform variables. This caller selects TLS 1.2 before downloading, stops on bootstrap failure, and dot-sources the downloaded tools in the caller's scope. Updating the repository alone will not change an existing RMM caller.
For download failures, use the standalone [Test-FileDownload.ps1](Test-FileDownload.ps1) diagnostic. See [the RMM caller, report guide, and shared caller audit](docs/FileDownload-Diagnostics.md). It compares the existing helper, BITS, and direct GET without changing production download behavior or running downloaded files. For download failures, use the standalone [Test-FileDownload.ps1](Test-FileDownload.ps1) diagnostic. See [the RMM caller, report guide, and shared caller audit](docs/FileDownload-Diagnostics.md). It compares the existing helper, BITS, and direct GET without changing production download behavior or running downloaded files.
`Get-DSAManifest.ps1` uses `Download-FileDirectly`, which passes the original URL to BITS without preliminary `Get-AbsoluteURI` or `IsURLValid` requests. It accepts the same URL and optional `-File` arguments as `Download-File`, waits for completion, and throws on BITS errors. If `-File` is omitted, its temporary filename comes from the original URL; supply `-File` for extensionless URLs or URLs with query strings. Existing `Download-File` callers retain their previous behavior. Publish `Tools.ps1` together with `Get-DSAManifest.ps1` so the new helper is available. `Get-DSAManifest.ps1` uses `Download-FileDirectly`, which passes the original URL to BITS without preliminary `Get-AbsoluteURI` or `IsURLValid` requests. It accepts the same URL and optional `-File` arguments as `Download-File`, waits for completion, and throws on BITS errors. If `-File` is omitted, its temporary filename comes from the original URL; supply `-File` for extensionless URLs or URLs with query strings. Existing `Download-File` callers retain their previous behavior. Publish `Tools.ps1` together with `Get-DSAManifest.ps1` so the new helper is available.
## Environment inventory
Use [Get-EnvironmentInventory.ps1](Get-EnvironmentInventory.ps1) to collect file
shares, networks, printer connections, wireless observations, and internet egress
into versioned JSON on Windows PowerShell 5.1. Reports describe the environment;
endpoint identity is optional and no Hudu credentials or module are required.
The [RMM caller](rmm/Get-EnvironmentInventory.ps1) supports optional upload through
the existing Filedrop helper. See the [options and data contract](docs/Environment-Inventory.md)
and [JSON schema](resources/environment-inventory/schema-v1.json). No importer is included.
## Microsoft 365 deployment ## Microsoft 365 deployment
See [Office365-Deployment.md](docs/Office365-Deployment.md) for the Syncro dropdowns and clean deployment workflow. Upload the shim in `rmm/Install-MicrosoftOffice365.ps1`; publish the core installer and `resources/office/Office-UserCleanup.ps1` together first. The shim uses the existing `Tools.ps1` unchanged; deployment, host relaunch, and result handling live in the main repository script. `ValidateBeforeChanges` defaults to `true` (checks and stages media only); explicitly select `false` to enable deployment. The workload runs in Windows PowerShell 5.1, requires an explicit subscription selection, removes Office and its companion apps, preserves Windows work-account sign-in, and installs the matching suite silently using Microsoft's current ODT. It then installs new Outlook and per-machine OneDrive using Microsoft's signed installers, plus current Teams only when the selected subscription includes Teams. Pending per-user cleanup is reported separately and protects the reinstalled apps. Action/error diagnostics use the existing Tools log; the result is printed to Syncro. See [Office365-Deployment.md](docs/Office365-Deployment.md) for the Syncro dropdowns and clean deployment workflow. Upload the shim in `rmm/Install-MicrosoftOffice365.ps1`; publish the core installer and `resources/office/Office-UserCleanup.ps1` together first. The shim uses the existing `Tools.ps1` unchanged; deployment, host relaunch, and result handling live in the main repository script. `ValidateBeforeChanges` defaults to `true` (assessment and HTTP HEAD checks without staging or downloads); explicitly select `false` to enable deployment. The workload runs in Windows PowerShell 5.1, requires an explicit subscription selection, removes Office and its companion apps, preserves Windows work-account sign-in, and installs the matching suite silently using Microsoft's current ODT. Confirmed removal corruption or residual state can trigger one Microsoft Get Help scrub before installation; its downloads are fresh and cleaned afterward, and a child window may appear. It then installs new Outlook and per-machine OneDrive using Microsoft's signed installers, plus current Teams only when the selected subscription includes Teams. Pending per-user cleanup is reported separately and protects the reinstalled apps. Action/error diagnostics use the existing Tools log; the result is printed to Syncro.
## OneDrive folder preparation ## OneDrive folder preparation
@@ -47,6 +68,22 @@ Each input returns a `System.Boolean`: `true`, `$true`, `yes`, `y`, and `1` beco
`Get-DSAManifest.ps1` uses this helper for its three options. Publish it together with the updated `Tools.ps1` so the helper is available to the RMM caller. `Get-DSAManifest.ps1` uses this helper for its three options. Publish it together with the updated `Tools.ps1` so the helper is available to the RMM caller.
## Converting RMM lists
Use `ConvertTo-RmmList` for an RMM string containing semicolon-separated values:
```powershell
$Paths = @(ConvertTo-RmmList -Value 'C:\QB Data; \\server\Archive;')
$Shares = @(ConvertTo-RmmList -Value $QuickBooksShareNames)
```
The helper trims surrounding whitespace and omits empty entries. It preserves
item order, duplicates, case, internal spaces, commas, and backslashes. It does
not evaluate text, resolve paths, or check whether files/shares exist. Semicolons
are always separators; there is no quoting or escaping syntax. Use `@(...)` so
zero, one, and multiple items always produce an array. Publish the updated
`Tools.ps1` with callers that use this new helper.
## Uploading files ## Uploading files
After dot-sourcing `Tools.ps1`, scripts can upload a completed file to the Emberkom FileDrop: After dot-sourcing `Tools.ps1`, scripts can upload a completed file to the Emberkom FileDrop:
@@ -72,5 +109,6 @@ powershell.exe -NoProfile -File .\tests\Upload-File.Tests.ps1
powershell.exe -NoProfile -File .\tests\Get-DSAManifest.Tests.ps1 powershell.exe -NoProfile -File .\tests\Get-DSAManifest.Tests.ps1
powershell.exe -NoProfile -File .\tests\Download-File.Tests.ps1 powershell.exe -NoProfile -File .\tests\Download-File.Tests.ps1
powershell.exe -NoProfile -File .\tests\ConvertTo-RmmBoolean.Tests.ps1 powershell.exe -NoProfile -File .\tests\ConvertTo-RmmBoolean.Tests.ps1
powershell.exe -NoProfile -File .\tests\ConvertTo-RmmList.Tests.ps1
powershell.exe -NoProfile -File .\tests\Get-AllNetworkDrives.Tests.ps1 powershell.exe -NoProfile -File .\tests\Get-AllNetworkDrives.Tests.ps1
``` ```
+250 -35
View File
@@ -7,6 +7,7 @@ Reads Cleanup* variables from the calling scope (including the RMM Run-Script
dot-source scope). Missing variables use Get-SystemCleanupDefaults. No param() dot-source scope). Missing variables use Get-SystemCleanupDefaults. No param()
block deliberately: RMM variables must not be overwritten by parameter defaults. block deliberately: RMM variables must not be overwritten by parameter defaults.
ReportOnly defaults to true and assesses enabled and disabled categories separately. ReportOnly defaults to true and assesses enabled and disabled categories separately.
Category rows include hibernation/VSS usage. Component-store savings are noted without running DISM analysis.
Server exclusions still apply. See rmm/Start-SystemCleanup.ps1 and Server exclusions still apply. See rmm/Start-SystemCleanup.ps1 and
docs/SystemCleanup.md for options, server exclusions, and legacy operation mapping. docs/SystemCleanup.md for options, server exclusions, and legacy operation mapping.
The core is self-contained; loading Tools.ps1 is the RMM shim's responsibility. The core is self-contained; loading Tools.ps1 is the RMM shim's responsibility.
@@ -19,6 +20,7 @@ function Get-SystemCleanupDefaults {
CleanupDiagnosticDays = 30 CleanupDiagnosticDays = 30
CleanupBackupDays = 30 CleanupBackupDays = 30
CleanupSystemTemp = $true CleanupSystemTemp = $true
CleanupOfficeStaging = $true
CleanupUserTemp = $true CleanupUserTemp = $true
CleanupServiceTemp = $true CleanupServiceTemp = $true
CleanupCBSArchives = $true CleanupCBSArchives = $true
@@ -153,9 +155,10 @@ function Get-SystemCleanupOS {
} }
function Write-SystemCleanupMessage { function Write-SystemCleanupMessage {
param([string]$Message) param([string]$Message, [switch]$Detail)
# Host/information stream keeps logs out of helper return values, even with Tools loaded. # Host/information stream keeps logs out of helper return values, even with Tools loaded.
Write-Host "[SystemCleanup] $Message" if ($Detail) { Write-Verbose "[SystemCleanup] $Message" }
else { Write-Host "[SystemCleanup] $Message" }
} }
function Test-SystemCleanupPath { function Test-SystemCleanupPath {
@@ -181,7 +184,9 @@ function Get-SystemCleanupChildren {
Write-SystemCleanupMessage "Skipping linked or unsafe path: $Root" Write-SystemCleanupMessage "Skipping linked or unsafe path: $Root"
return 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 { function Get-SystemCleanupFiles {
@@ -199,6 +204,7 @@ function Get-SystemCleanupFiles {
function Remove-SystemCleanupFile { function Remove-SystemCleanupFile {
param($Context, [string]$Category, [string]$Root, [string]$Path, [datetime]$Cutoff) 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 } if (-not (Test-SystemCleanupPath $Path $Root)) { return }
$file = Get-Item -LiteralPath $Path -Force -ErrorAction Stop $file = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
if ($file.PSIsContainer -or $file.LastWriteTimeUtc -ge $Cutoff) { return } if ($file.PSIsContainer -or $file.LastWriteTimeUtc -ge $Cutoff) { return }
@@ -255,6 +261,7 @@ function Invoke-SystemCleanupCategory {
Category = $Name; Enabled = $enabled Category = $Name; Enabled = $enabled
CandidateFiles = $(if ($native -or $blocked) { $null } else { 0 }) CandidateFiles = $(if ($native -or $blocked) { $null } else { 0 })
CandidateBytes = $(if ($native -or $blocked) { $null } else { [long]0 }) CandidateBytes = $(if ($native -or $blocked) { $null } else { [long]0 })
UsageBytes = $null; UsageNote = ''
RemovedFiles = 0; RemovedBytes = [long]0; FailedFiles = 0 RemovedFiles = 0; RemovedBytes = [long]0; FailedFiles = 0
Status = $(if ($Context.Options.ReportOnly) { 'Preview' } else { 'Completed' }) Status = $(if ($Context.Options.ReportOnly) { 'Preview' } else { 'Completed' })
EstimateStatus = $(if ($native) { 'Not estimated' } else { 'Estimated' }) EstimateStatus = $(if ($native) { 'Not estimated' } else { 'Estimated' })
@@ -263,21 +270,21 @@ function Invoke-SystemCleanupCategory {
if ($blocked) { if ($blocked) {
$Context.Stats[$Name].Status = 'Blocked on server' $Context.Stats[$Name].Status = 'Blocked on server'
$Context.Stats[$Name].EstimateStatus = 'Not assessed' $Context.Stats[$Name].EstimateStatus = 'Not assessed'
Write-SystemCleanupMessage "BLOCKED on server OS: $Name ($setting)" Write-SystemCleanupMessage "BLOCKED on server OS: $Name ($setting)" -Detail:$Context.Options.ReportOnly
return return
} }
if ($Context.Options.ReportOnly) { if ($Context.Options.ReportOnly) {
if (-not $Context.ContainsKey('Candidates')) { $Context.Candidates = @{} } if (-not $Context.ContainsKey('Candidates')) { $Context.Candidates = @{} }
$Context.Candidates[$Name] = New-Object 'System.Collections.Generic.Dictionary[string,long]' ([StringComparer]::OrdinalIgnoreCase) $Context.Candidates[$Name] = New-Object 'System.Collections.Generic.Dictionary[string,long]' ([StringComparer]::OrdinalIgnoreCase)
$selection = if ($enabled) { 'enabled for apply' } else { 'disabled; assessment only' } $selection = if ($enabled) { 'enabled for apply' } else { 'disabled; assessment only' }
Write-SystemCleanupMessage "Assessing $Name ($selection)." Write-SystemCleanupMessage "Assessing $Name ($selection)." -Detail
} }
try { & $Action } catch { try { & $Action } catch {
$Context.Stats[$Name].Status = 'Failed' $Context.Stats[$Name].Status = 'Failed'
$Context.Stats[$Name].EstimateStatus = 'Incomplete' $Context.Stats[$Name].EstimateStatus = 'Incomplete'
$Context.Stats[$Name].Notes = $_.Exception.Message $Context.Stats[$Name].Notes = $_.Exception.Message
$Context.Errors++ $Context.Errors++
Write-SystemCleanupMessage "$Name failed: $($_.Exception.Message)" Write-SystemCleanupMessage "$Name failed: $($_.Exception.Message)" -Detail:$Context.Options.ReportOnly
} }
if (-not $Context.Options.ReportOnly) { if (-not $Context.Options.ReportOnly) {
$s = $Context.Stats[$Name] $s = $Context.Stats[$Name]
@@ -291,7 +298,7 @@ function Set-SystemCleanupSkipped {
$Context.Stats[$Category].Status = $Status $Context.Stats[$Category].Status = $Status
$Context.Stats[$Category].EstimateStatus = 'Not assessed' $Context.Stats[$Category].EstimateStatus = 'Not assessed'
$Context.Stats[$Category].Notes = $Reason $Context.Stats[$Category].Notes = $Reason
Write-SystemCleanupMessage $Reason Write-SystemCleanupMessage $Reason -Detail:$Context.Options.ReportOnly
} }
function Get-SystemCleanupReportTotals { function Get-SystemCleanupReportTotals {
@@ -314,38 +321,139 @@ function Get-SystemCleanupReportTotals {
} }
} }
function Get-SystemCleanupVolumeId {
param($Reference)
# CIM references can be embedded instances or escaped WMI object-path strings.
$text = if ($Reference -is [string]) { $Reference } elseif ($Reference.DeviceID) { [string]$Reference.DeviceID } else { [string]$Reference }
$match = [regex]::Match($text, '(?i)Volume\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}')
if (-not $match.Success) { throw 'Cannot identify the volume in a shadow-storage reference.' }
return $match.Value.ToLowerInvariant()
}
function Get-SystemCleanupShadowStorageDiagnostic {
$volumes = @(Get-CimInstance -ClassName Win32_Volume -ErrorAction Stop)
$systemVolume = @($volumes | Where-Object { $_.DriveLetter -eq $env:SystemDrive })
if ($systemVolume.Count -ne 1) { throw 'Cannot uniquely identify the system volume.' }
$systemId = Get-SystemCleanupVolumeId $systemVolume[0]
$storage = @(Get-CimInstance -ClassName Win32_ShadowStorage -ErrorAction Stop | Where-Object {
(Get-SystemCleanupVolumeId $_.Volume) -eq $systemId
})
if (-not $storage.Count) { return [pscustomobject]@{UsedBytes=[decimal]0; AllocatedBytes=[decimal]0; StoredOn=''} }
$used = [decimal]0; $allocated = [decimal]0; $locations = @()
foreach ($item in $storage) {
# A missing measurement must not be converted to zero.
foreach ($property in @('UsedSpace', 'AllocatedSpace')) {
$bytes = [uint64]0
if (-not [uint64]::TryParse([string]$item.$property, [ref]$bytes)) { throw "Invalid shadow-storage $property." }
if ($property -eq 'UsedSpace') { $used += $bytes } else { $allocated += $bytes }
}
$targetId = Get-SystemCleanupVolumeId $item.DiffVolume
$target = @($volumes | Where-Object { (Get-SystemCleanupVolumeId $_) -eq $targetId })
$locations += if ($target.Count -eq 1 -and $target[0].DriveLetter) { $target[0].DriveLetter } else { 'unmounted/unknown volume' }
}
return [pscustomobject]@{UsedBytes=$used; AllocatedBytes=$allocated; StoredOn=(($locations | Select-Object -Unique) -join ', ')}
}
function Get-SystemCleanupDiagnostics {
param($Context)
$diagnostics = [ordered]@{}
if (-not $Context.Options.ReportOnly) { return $diagnostics }
if (-not $Context.OS.IsServer) {
# Store usage separately from candidate savings so totals do not overpromise.
$hibernation = $Context.Stats['DisableHibernation']
$hibernation.UsageBytes = $null
$hibernation.UsageNote = 'file size; excluded from totals'
try {
$path = Join-Path $env:SystemDrive 'hiberfil.sys'
$file = Get-Item -LiteralPath $path -Force -ErrorAction Stop
if ($file.PSIsContainer -or ($file.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Unexpected hibernation file type.' }
$hibernation.UsageBytes = [long]$file.Length
} catch [System.Management.Automation.ItemNotFoundException] {
$hibernation.UsageBytes = [long]0
} catch {
Write-SystemCleanupMessage "Hibernation diagnostic: $($_.Exception.Message)" -Detail
$hibernation.UsageNote = 'unavailable (file inspection failed; see verbose)'
}
$shadows = $Context.Stats['ShadowCopies']
$shadows.UsageBytes = $null
$shadows.UsageNote = 'VSS used; excluded from totals'
try {
$storage = Get-SystemCleanupShadowStorageDiagnostic
$shadows.UsageBytes = $storage.UsedBytes
if ($storage.UsedBytes -gt 0) { $shadows.UsageNote += '; newest retained' }
if ($storage.StoredOn) { $shadows.UsageNote += '; stored on ' + $storage.StoredOn }
Write-SystemCleanupMessage ('Shadow storage for {0}: {1:N2} MiB used / {2:N2} MiB allocated; stored on {3}' -f $env:SystemDrive, ($storage.UsedBytes / 1MB), ($storage.AllocatedBytes / 1MB), $storage.StoredOn) -Detail
} catch {
Write-SystemCleanupMessage "Shadow-storage diagnostic: $($_.Exception.Message)" -Detail
$shadows.UsageNote = 'unavailable (storage inspection failed; see verbose)'
}
}
# Avoid slow DISM analysis during previews; potential savings are not measured.
$diagnostics.ComponentStore = 'not analyzed; removing superseded updates may free substantial space, or little/none.'
return $diagnostics
}
function Write-SystemCleanupReport { function Write-SystemCleanupReport {
param($Context) param($Context)
Write-SystemCleanupMessage 'REPORT ONLY: no cleanup performed. Category estimates use the configured retention periods.' Write-SystemCleanupMessage 'REPORT ONLY - no cleanup performed.'
$totals = Get-SystemCleanupReportTotals $Context
Write-SystemCleanupMessage ('Known savings: ENABLED {0:N2} MiB ({1:N0} files); additional DISABLED {2:N2} MiB ({3:N0} files).' -f ($totals.EnabledBytes / 1MB), $totals.EnabledFiles, ($totals.AdditionalDisabledBytes / 1MB), $totals.AdditionalDisabledFiles)
if ($Context.ContainsKey('Diagnostics') -and $Context.Diagnostics.Count) {
Write-SystemCleanupMessage 'DIAGNOSTICS - potential, excluded from savings totals'
foreach ($entry in $Context.Diagnostics.GetEnumerator()) {
Write-SystemCleanupMessage (" {0}: {1}" -f $entry.Key, $entry.Value)
}
}
Write-SystemCleanupMessage "Retention: temp $($Context.Options.TempDays)d; diagnostics $($Context.Options.DiagnosticDays)d; backups $($Context.Options.BackupDays)d."
Write-SystemCleanupMessage ('{0,-25} {1,8} {2,11} {3}' -f 'Category', 'Files', 'MiB', 'Notes')
foreach ($group in @('Enabled', 'Disabled', 'Blocked')) { foreach ($group in @('Enabled', 'Disabled', 'Blocked')) {
$rows = @($Context.Stats.Values | Where-Object { $rows = @($Context.Stats.Values | Where-Object {
if ($group -eq 'Blocked') { $_.Status -eq 'Blocked on server' } if ($group -eq 'Blocked') { $_.Status -eq 'Blocked on server' }
else { $_.Status -ne 'Blocked on server' -and $_.Enabled -eq ($group -eq 'Enabled') } else { $_.Status -ne 'Blocked on server' -and $_.Enabled -eq ($group -eq 'Enabled') }
} | Sort-Object Category) } | Sort-Object Category)
$heading = switch ($group) { $heading = switch ($group) {
Enabled { 'ENABLED - eligible for cleanup when CleanupReportOnly=false, subject to the listed conditions' } Enabled { 'ENABLED - would run with current settings' }
Disabled { 'DISABLED - potential savings only; these categories will not run until enabled' } Disabled { 'DISABLED - potential only; will not run' }
Blocked { 'BLOCKED ON SERVER - not assessed and cannot be enabled on this OS' } Blocked { 'BLOCKED ON SERVER - cannot run' }
} }
Write-SystemCleanupMessage $heading Write-SystemCleanupMessage $heading
if (-not $rows.Count) { Write-SystemCleanupMessage ' None.' } if (-not $rows.Count) { Write-SystemCleanupMessage ' None.' }
foreach ($row in $rows) { foreach ($row in $rows) {
$estimate = switch ($row.EstimateStatus) { $files = '-'; $size = '-'; $notes = @(); $bytes = $null
'Not estimated' { 'space savings not estimated' } if ($row.UsageNote) {
'Not assessed' { 'space savings not assessed' } $bytes = $row.UsageBytes
default { $notes += $row.UsageNote
if ($null -eq $row.CandidateBytes) { 'space savings unavailable' } } elseif ($row.EstimateStatus -eq 'Not estimated') { $notes += 'not estimated' }
else { '{0} eligible files / {1:N2} MiB' -f $row.CandidateFiles, ($row.CandidateBytes / 1MB) } elseif ($row.EstimateStatus -eq 'Not assessed') { $notes += 'not assessed' }
} elseif ($null -ne $row.CandidateBytes) {
$files = '{0:N0}' -f $row.CandidateFiles
$bytes = $row.CandidateBytes
} else { $notes += 'unavailable' }
if ($null -ne $bytes) { $size = if ($bytes -gt 0 -and $bytes -lt (0.01 * 1MB)) { '<0.01' } else { '{0:N2}' -f ($bytes / 1MB) } }
if ($row.Status -notin @('Preview', 'Blocked on server')) { $notes += $row.Status }
if ($row.EstimateStatus -eq 'Incomplete') { $notes += 'incomplete' }
if ($row.FailedFiles) { $notes += "$($row.FailedFiles) files skipped" }
if ($row.Category -eq 'DiskCleanup') {
$notes += "$($Context.Options.DiskCleanupPreset) ($(@($Context.Options.DiskCleanupItems).Count) handlers)"
if (-not $row.Enabled) { $notes += 'will not run' }
# The selected handler list is configuration detail, not a warning.
if ($row.Status -eq 'Failed') { $notes += $row.Notes }
else { Write-SystemCleanupMessage "Disk Cleanup: $($row.Notes)" -Detail }
} elseif ($row.Category -eq 'ComponentStore') {
$notes += 'background task on apply'
if ($row.Notes) { $notes += $row.Notes }
} elseif ($row.Notes) { $notes += $row.Notes }
# Keep every category on one line, including multiline native errors.
$noteText = ($notes -join '; ') -replace '\s+', ' '
if ($noteText.Length -gt 180) {
Write-SystemCleanupMessage "$($row.Category): $noteText" -Detail
$noteText = $noteText.Substring(0, 163) + '... (see verbose)'
} }
if ($row.EstimateStatus -eq 'Incomplete') { $estimate += ' (incomplete assessment)' } Write-SystemCleanupMessage ('{0,-25} {1,8} {2,11} {3}' -f $row.Category, $files, $size, $noteText.Trim())
Write-SystemCleanupMessage " $($row.Category) [$($row.Setting)]: $estimate; $($row.Status). $($row.Notes)"
} }
} }
$totals = Get-SystemCleanupReportTotals $Context Write-SystemCleanupMessage 'Totals count each path once; rows may overlap. Unknown/unassessed savings excluded; disk space freed may differ.'
Write-SystemCleanupMessage ('Known unique file estimates in ENABLED categories: {0} files / {1:N2} MiB.' -f $totals.EnabledFiles, ($totals.EnabledBytes / 1MB)) Write-SystemCleanupMessage 'Settings: Cleanup<Category>; DiskCleanup uses CleanupDiskCleanupItems. Full diagnostics: $VerbosePreference="Continue".'
Write-SystemCleanupMessage ('Additional unique file estimates in DISABLED categories, beyond enabled categories: {0} files / {1:N2} MiB.' -f $totals.AdditionalDisabledFiles, ($totals.AdditionalDisabledBytes / 1MB))
Write-SystemCleanupMessage 'Category estimates can overlap; the totals count each path once. Native savings and unassessed data are excluded; actual freed disk space may differ.'
} }
function Test-SystemCleanupAppRunning { function Test-SystemCleanupAppRunning {
@@ -359,7 +467,7 @@ function Invoke-SystemCleanupProcess {
$nativeDir = if ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess) { 'Sysnative' } else { 'System32' } $nativeDir = if ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess) { 'Sysnative' } else { 'System32' }
$executable = Join-Path $env:SystemRoot "$nativeDir\$FileName" $executable = Join-Path $env:SystemRoot "$nativeDir\$FileName"
if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) { throw "Unavailable: $executable" } if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) { throw "Unavailable: $executable" }
Write-SystemCleanupMessage "$FileName $Arguments (native operation; size not estimated)" Write-SystemCleanupMessage "$FileName $Arguments (native operation; size not estimated)" -Detail:$Context.Options.ReportOnly
if ($Context.Options.ReportOnly) { return } if ($Context.Options.ReportOnly) { return }
$process = Start-Process -FilePath $executable -ArgumentList $Arguments -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop $process = Start-Process -FilePath $executable -ArgumentList $Arguments -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop
if ($process.ExitCode -ne 0) { throw "$FileName returned exit code $($process.ExitCode)." } if ($process.ExitCode -ne 0) { throw "$FileName returned exit code $($process.ExitCode)." }
@@ -429,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 { function Get-SystemCleanupRecycleDate {
param([string]$MetadataPath) param([string]$MetadataPath)
if ((Get-Item -LiteralPath $MetadataPath -Force -ErrorAction Stop).Length -gt 1MB) { throw 'Oversized Recycle Bin metadata.' } if ((Get-Item -LiteralPath $MetadataPath -Force -ErrorAction Stop).Length -gt 1MB) { throw 'Oversized Recycle Bin metadata.' }
@@ -473,10 +675,10 @@ function Invoke-SystemCleanupDiskCleanup {
# Defence in depth: even direct helper calls cannot run cleanmgr on a server. # Defence in depth: even direct helper calls cannot run cleanmgr on a server.
if ($Context.OS.IsServer) { throw 'Disk Cleanup is blocked on server OSes.' } if ($Context.OS.IsServer) { throw 'Disk Cleanup is blocked on server OSes.' }
$selected = @($Context.Options.DiskCleanupItems) $selected = @($Context.Options.DiskCleanupItems)
Write-SystemCleanupMessage "Disk Cleanup selection: $($Context.Options.DiskCleanupPreset); selected items: $($selected -join ', '). Windows controls retention for these handlers." Write-SystemCleanupMessage "Disk Cleanup selection: $($Context.Options.DiskCleanupPreset); selected items: $($selected -join ', '). Windows controls retention for these handlers." -Detail
if ($Context.Options.ReportOnly) { if ($Context.Options.ReportOnly) {
$unselected = @((Get-SystemCleanupHandlers) | Where-Object { $_ -notin $selected }) $unselected = @((Get-SystemCleanupHandlers) | Where-Object { $_ -notin $selected })
Write-SystemCleanupMessage "Disk Cleanup items not selected (not run during apply): $($unselected -join ', '). Handler savings are not estimated." Write-SystemCleanupMessage "Disk Cleanup items not selected (not run during apply): $($unselected -join ', '). Handler savings are not estimated." -Detail
return return
} }
if (-not $selected.Count) { return } if (-not $selected.Count) { return }
@@ -535,7 +737,7 @@ function Invoke-SystemCleanupSearchCompaction {
if (-not (Test-Path -LiteralPath $database -PathType Leaf)) { return } if (-not (Test-Path -LiteralPath $database -PathType Leaf)) { return }
if (-not (Test-SystemCleanupPath $database (Split-Path -Parent $database))) { return } if (-not (Test-SystemCleanupPath $database (Split-Path -Parent $database))) { return }
if ($Context.Options.ReportOnly) { if ($Context.Options.ReportOnly) {
Write-SystemCleanupMessage "Would compact $database; size savings cannot be estimated." Write-SystemCleanupMessage "Would compact $database; size savings cannot be estimated." -Detail
return return
} }
$drive = New-Object IO.DriveInfo ([IO.Path]::GetPathRoot($database)) $drive = New-Object IO.DriveInfo ([IO.Path]::GetPathRoot($database))
@@ -596,9 +798,14 @@ function Invoke-SystemCleanup {
# Generic temp cleaning must not bypass the AutoCAD process check or dump retention. # Generic temp cleaning must not bypass the AutoCAD process check or dump retention.
$tempExclusions = @('*.ac$', '*.sv$', '*.dmp') $tempExclusions = @('*.ac$', '*.sv$', '*.dmp')
Invoke-SystemCleanupCategory $context 'SystemTemp' { 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. # 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' { Invoke-SystemCleanupCategory $context 'UserTemp' {
$acadRunning = Test-SystemCleanupAppRunning @('acad') $acadRunning = Test-SystemCleanupAppRunning @('acad')
foreach ($profile in $profiles) { foreach ($profile in $profiles) {
@@ -619,7 +826,10 @@ function Invoke-SystemCleanup {
# Do not stop Windows servicing to reclaim a log. Remove only when already idle. # Do not stop Windows servicing to reclaim a log. Remove only when already idle.
if ($total -ge 200MB -and (Get-Service -Name TrustedInstaller -ErrorAction Stop).Status -eq 'Stopped') { if ($total -ge 200MB -and (Get-Service -Name TrustedInstaller -ErrorAction Stop).Status -eq 'Stopped') {
Clear-SystemCleanupTree $context 'ActiveCBSLog' $cbs $diagnosticCutoff -Include @('CBS.log') Clear-SystemCleanupTree $context 'ActiveCBSLog' $cbs $diagnosticCutoff -Include @('CBS.log')
} else { Write-SystemCleanupMessage 'Active CBS.log retained: servicing is active or archives total less than 200 MiB.' } } else {
$context.Stats.ActiveCBSLog.Notes = 'Retained: servicing active or CBS archives below 200 MiB.'
Write-SystemCleanupMessage 'Active CBS.log retained: servicing is active or archives total less than 200 MiB.' -Detail:$Options.ReportOnly
}
} }
Invoke-SystemCleanupCategory $context 'CBSArchives' { Invoke-SystemCleanupCategory $context 'CBSArchives' {
Clear-SystemCleanupTree $context 'CBSArchives' (Join-Path $env:SystemRoot 'Logs\CBS') $diagnosticCutoff -Include @('CbsPersist_*.log', 'CbsPersist_*.cab') Clear-SystemCleanupTree $context 'CBSArchives' (Join-Path $env:SystemRoot 'Logs\CBS') $diagnosticCutoff -Include @('CbsPersist_*.log', 'CbsPersist_*.cab')
@@ -686,7 +896,7 @@ function Invoke-SystemCleanup {
$context.Stats.BrowserCache.Status = 'Partial' $context.Stats.BrowserCache.Status = 'Partial'
$context.Stats.BrowserCache.EstimateStatus = 'Incomplete' $context.Stats.BrowserCache.EstimateStatus = 'Incomplete'
$context.Stats.BrowserCache.Notes += "$($browser.Name) is running; its cache was not assessed. " $context.Stats.BrowserCache.Notes += "$($browser.Name) is running; its cache was not assessed. "
Write-SystemCleanupMessage "$($browser.Name) is running; its caches retained." Write-SystemCleanupMessage "$($browser.Name) is running; its caches retained." -Detail:$Options.ReportOnly
continue continue
} }
foreach ($profile in $profiles) { foreach ($profile in $profiles) {
@@ -716,15 +926,18 @@ function Invoke-SystemCleanup {
if ($Options.ReportOnly) { Set-SystemCleanupSkipped $context 'DeliveryOptimization' 'Delivery Optimization cmdlet is not installed.' -Status 'Unavailable'; return } if ($Options.ReportOnly) { Set-SystemCleanupSkipped $context 'DeliveryOptimization' 'Delivery Optimization cmdlet is not installed.' -Status 'Unavailable'; return }
throw 'Delivery Optimization cmdlet is not installed.' throw 'Delivery Optimization cmdlet is not installed.'
} }
Write-SystemCleanupMessage 'Delivery Optimization: unpinned cache only; size not estimated.' Write-SystemCleanupMessage 'Delivery Optimization: unpinned cache only; size not estimated.' -Detail:$Options.ReportOnly
if (-not $Options.ReportOnly) { Delete-DeliveryOptimizationCache -Force -ErrorAction Stop } if (-not $Options.ReportOnly) { Delete-DeliveryOptimizationCache -Force -ErrorAction Stop }
} }
Invoke-SystemCleanupCategory $context 'ComponentStore' { Invoke-SystemCleanupCategory $context 'ComponentStore' {
Invoke-SystemCleanupProcess $context 'schtasks.exe' '/Run /TN "\Microsoft\Windows\Servicing\StartComponentCleanup"' Invoke-SystemCleanupProcess $context 'schtasks.exe' '/Run /TN "\Microsoft\Windows\Servicing\StartComponentCleanup"'
Write-SystemCleanupMessage 'Component cleanup runs asynchronously under Task Scheduler; completion and reclaimed bytes are not measured here.' Write-SystemCleanupMessage 'Component cleanup runs asynchronously under Task Scheduler; completion and reclaimed bytes are not measured here.' -Detail:$Options.ReportOnly
} }
Invoke-SystemCleanupCategory $context 'DiskCleanup' { Invoke-SystemCleanupDiskCleanup $context } Invoke-SystemCleanupCategory $context 'DiskCleanup' { Invoke-SystemCleanupDiskCleanup $context }
if ($Options.ReportOnly) { Write-SystemCleanupReport $context } if ($Options.ReportOnly) {
$context.Diagnostics = Get-SystemCleanupDiagnostics $context
Write-SystemCleanupReport $context
}
if ($context.Errors) { throw "$($context.Errors) cleanup category/maintenance error(s). Review the category messages above." } if ($context.Errors) { throw "$($context.Errors) cleanup category/maintenance error(s). Review the category messages above." }
return @($context.Stats.Values | Sort-Object @{Expression={ if ($_.Status -eq 'Blocked on server') { 2 } elseif ($_.Enabled) { 0 } else { 1 } }}, Category) return @($context.Stats.Values | Sort-Object @{Expression={ if ($_.Status -eq 'Blocked on server') { 2 } elseif ($_.Enabled) { 0 } else { 1 } }}, Category)
} finally { } finally {
@@ -734,4 +947,6 @@ function Invoke-SystemCleanup {
} }
# Read inherited caller variables before entering the implementation's local scope. # Read inherited caller variables before entering the implementation's local scope.
Invoke-SystemCleanup -Options (Get-SystemCleanupOptions) # The function returns structured results for programmatic callers/tests. Do not
# let PowerShell auto-format a second, much longer report in the RMM output.
Invoke-SystemCleanup -Options (Get-SystemCleanupOptions) | Out-Null
+113
View File
@@ -219,6 +219,38 @@ Function ConvertTo-RmmBoolean {
} }
} }
# Convert an RMM semicolon-separated text variable into individual strings.
Function ConvertTo-RmmList {
<#
.SYNOPSIS
Splits an RMM text value on semicolons and trims each item.
.DESCRIPTION
Null, blank, and empty items are omitted. Item order, case, duplicates,
internal spaces, commas, and backslashes are preserved. Values are not
evaluated, expanded, resolved, or checked for existence. Semicolons are
always separators; there is no quoting or escaping syntax.
Wrap the call in @() to obtain an array for zero, one, or many items.
.EXAMPLE
$Paths = @(ConvertTo-RmmList -Value 'C:\QB Data; \\server\Archive;')
.EXAMPLE
$Shares = @(ConvertTo-RmmList -Value $QuickBooksShareNames)
#>
[CmdletBinding()]
[OutputType([string])]
param(
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
[AllowNull()]
[AllowEmptyString()]
[string]$Value
)
process {
foreach ($Item in ([string]$Value).Split(';')) {
$Item = $Item.Trim()
if ($Item.Length -gt 0) { $Item }
}
}
}
# Determines whether a URL is valid # Determines whether a URL is valid
Function IsURLValid { Function IsURLValid {
param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$URL) param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$URL)
@@ -853,6 +885,87 @@ Function Disable-Log {
Catch { Write-Error $_.Exception.Message } Catch { Write-Error $_.Exception.Message }
} }
# Published packages for both Install- and Update-EmberkomCloudBackup.
Function Get-EmberkomCloudBackupReleases {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$client = New-Object Net.WebClient
try {
$json = $client.DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/resources/EmberkomCloudBackup.json')
} finally { $client.Dispose() }
$manifest = $json | ConvertFrom-Json -ErrorAction Stop
$releases = @{}
foreach ($build in 'Windows','VM') {
$release = $manifest.$build
$version = $null
if ([version]::TryParse($release.Version, [ref]$version) -and $version.Revision -ge 0 -and $release.Url -match '^https://' -and
$release.SHA256 -match '^[a-f0-9]{64}$') {
$releases[$build] = $release
}
}
return $releases
}
Function Get-EmberkomCloudBackupRelease {
param(
[Parameter(Mandatory=$true)][ValidateSet('Windows','VM')][string]$Build,
[hashtable]$Releases = (Get-EmberkomCloudBackupReleases)
)
if (!$Releases[$Build]) { throw "Incomplete Emberkom Cloud Backup release for $Build." }
return $Releases[$Build]
}
Function Save-EmberkomCloudBackupInstaller {
param([Parameter(Mandatory=$true)]$Release, [Parameter(Mandatory=$true)][string]$Path)
$ProgressPreference = 'SilentlyContinue'
$sourceHost = ([uri]$Release.Url).Host
$maxAttempts = 2
$timeoutSeconds = 240
Write-Host "MSP360 $($Release.Version) installer target: $Path (expected SHA-256 $($Release.SHA256))."
try {
for ($attempt = 1; $attempt -le $maxAttempts; $attempt++) {
$elapsed = [Diagnostics.Stopwatch]::StartNew()
$utc = [datetime]::UtcNow.ToString('u')
Write-Host "$utc $env:COMPUTERNAME - MSP360 installer download from $sourceHost (attempt $attempt of $maxAttempts, request timeout $timeoutSeconds seconds)."
try {
Invoke-WebRequest -UseBasicParsing -Uri $Release.Url -OutFile $Path -TimeoutSec $timeoutSeconds -ErrorAction Stop
break
} catch {
$failure = $_.Exception
while ($failure.InnerException -and $failure -isnot [Net.WebException]) { $failure = $failure.InnerException }
$failureHost = $sourceHost
if ($failure -is [Net.WebException]) {
$reason = [string]$failure.Status
$retry = $reason -in @('Timeout','NameResolutionFailure','ProxyNameResolutionFailure','ConnectFailure',
'ConnectionClosed','KeepAliveFailure','SendFailure','ReceiveFailure','PipelineFailure')
if ($failure.Response -is [Net.HttpWebResponse]) {
$status = [int]$failure.Response.StatusCode
$failureHost = $failure.Response.ResponseUri.Host
$failure.Response.Close()
$reason = "HTTP $status"
$retry = $status -in @(408,429,500,502,503,504)
}
} elseif ($failure -is [Net.Sockets.SocketException]) {
$reason = [string]$failure.SocketErrorCode
$retry = $true
} else { throw }
$bytes = if (Test-Path -LiteralPath $Path) { (Get-Item -LiteralPath $Path).Length } else { 0 }
$detail = "MSP360 download attempt $attempt of $maxAttempts from $failureHost failed ($reason) after $([int]$elapsed.Elapsed.TotalSeconds)s, $bytes bytes saved."
if (!$retry -or $attempt -eq $maxAttempts) { throw $detail }
Write-Host "$detail Retrying in 3 seconds."
if (Test-Path -LiteralPath $Path) { Remove-Item -LiteralPath $Path -Force -ErrorAction Stop }
Start-Sleep -Seconds 3
}
}
if ((Get-FileHash -LiteralPath $Path -Algorithm SHA256 -ErrorAction Stop).Hash -ne $Release.SHA256) {
throw 'The installer SHA-256 does not match the published release.'
}
Write-Host 'MSP360 installer download complete. SHA-256 verified.'
} catch {
if (Test-Path -LiteralPath $Path) { Remove-Item -LiteralPath $Path -Force -ErrorAction Stop }
throw
}
}
# Function to install the MSP360 Powershell module # Function to install the MSP360 Powershell module
Function Import-MSP360Module { Function Import-MSP360Module {
Try { Try {
+138
View File
@@ -0,0 +1,138 @@
#Requires -Version 4.0
# Update an existing Emberkom MSP360 Managed Backup agent during an idle RMM window.
function Get-CloudBackupInstallation {
# MSP360's managed-agent registration points to the branded uninstall key.
# Open the registry view explicitly so a 32-bit RMM host can see a 64-bit agent.
$views = if ([Environment]::Is64BitOperatingSystem) { 'Registry64', 'Registry32' } else { 'Registry32' }
foreach ($view in $views) {
$registry = [Microsoft.Win32.RegistryKey]::OpenBaseKey('LocalMachine', $view)
$marker = $product = $null
try {
$marker = $registry.OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{07BCB989-197A-4E3D-852D-DE8363860401}')
if (!$marker) { continue }
$product = $registry.OpenSubKey([string]$marker.GetValue('UninstallKey'))
if (!$product -or !$product.GetValue('')) { throw 'The MSP360 agent registration has no executable path.' }
if ($product.GetValue('Publisher') -ne 'Emberkom') { throw 'The registered backup agent belongs to a different publisher.' }
$cli = Join-Path (Split-Path -LiteralPath $product.GetValue('')) 'cbb.exe'
return [pscustomobject]@{
Cli = $cli
Version = [version][Diagnostics.FileVersionInfo]::GetVersionInfo($cli).FileVersion
}
} finally {
if ($product) { $product.Dispose() }
if ($marker) { $marker.Dispose() }
$registry.Dispose()
}
}
}
function Read-CloudBackupAgent {
param($Installation)
if (!$Installation) { return }
$details = & $Installation.Cli ver
if ($LASTEXITCODE -ne 0) { throw "MSP360 could not report the installed agent details (exit $LASTEXITCODE)." }
$edition = $service = $null
foreach ($line in $details) {
if ($line -match '^Backup Agent Edition:\s*(.+)$') { $edition = $Matches[1].Trim() }
if ($line -match '^Service name:\s*(.+)$') { $service = $Matches[1].Trim() }
}
if ($edition -in @('VMware','VMEdition','VM','Virtual Machine Edition')) {
$build = 'VM'
} elseif ($edition -in @('Desktop','DesktopIBB','FileBackup','BareMetal','Server','MsSql','SqlServer',
'Exchange','MsExchange','SqlExchange','MsSqlExchange','MsSqlMsExchange','Enterprise','Ultimate')) {
$build = 'Windows'
} else {
throw "Unrecognized MSP360 agent edition '$edition'. Cannot choose a published package."
}
if (!$service) { throw 'MSP360 did not report its backup service name.' }
[pscustomobject]@{
Version = $Installation.Version
Build = $build
Service = $service
}
}
function Test-CloudBackupUpdateWindow {
param([string]$Window, [datetime]$Now = (Get-Date))
if ([string]::IsNullOrWhiteSpace($Window)) { return $true }
if ($Window.Trim() -notmatch '^((?:[01]\d|2[0-3]):[0-5]\d)-((?:[01]\d|2[0-3]):[0-5]\d)$') {
throw 'MSP360UpdateWindow must be a local 24-hour interval such as 12:00-13:00.'
}
$start = [timespan]::ParseExact($Matches[1], 'hh\:mm', $null)
$end = [timespan]::ParseExact($Matches[2], 'hh\:mm', $null)
if ($start -eq $end) { throw 'MSP360UpdateWindow needs different start and end times.' }
$time = $Now.TimeOfDay
if ($start -lt $end) { return ($time -ge $start -and $time -lt $end) }
return ($time -ge $start -or $time -lt $end)
}
function Test-CloudBackupPlanRunning {
# The agent launches CBBackupPlan.exe for plan execution. This also works on
# CLI-password-protected agents, without passing credentials to a child process.
return [bool](Get-CimInstance -ClassName Win32_Process -Filter "Name = 'CBBackupPlan.exe'" -Property ProcessId -ErrorAction Stop)
}
function Invoke-CloudBackupUpdate {
param([string]$Window)
if (!(Test-CloudBackupUpdateWindow $Window)) { Write-Host "Deferred. Outside the local update window $Window."; return 0 }
$installation = Get-CloudBackupInstallation
if (!$installation) { Write-Host 'Skipped. MSP360 Managed Backup is not installed.'; return 0 }
$releases = Get-EmberkomCloudBackupReleases
# If neither package is newer, the daily check can finish without launching cbb.exe.
if ($releases.Count -eq 2 -and $installation.Version -ge [version]$releases.Windows.Version -and
$installation.Version -ge [version]$releases.VM.Version) {
Write-Host "No update needed. Installed $($installation.Version), published Windows $($releases.Windows.Version), VM $($releases.VM.Version)."
return 0
}
$agent = Read-CloudBackupAgent $installation
$release = Get-EmberkomCloudBackupRelease -Build $agent.Build -Releases $releases
$target = [version]$release.Version
if ($agent.Version -ge $target) {
Write-Host "No update needed. Installed $($agent.Version), published $($agent.Build) build $target."
return 0
}
if (Test-CloudBackupPlanRunning) { Write-Host 'Deferred. An MSP360 plan worker is active.'; return 0 }
$installer = Join-Path ([IO.Path]::GetTempPath()) ("EmberkomCloudBackup-{0}.exe" -f [guid]::NewGuid())
try {
Write-Host "Downloading the published $($agent.Build) update from $($agent.Version) to $target."
Save-EmberkomCloudBackupInstaller -Release $release -Path $installer
# A scheduled plan or the agent's own updater could have started during download.
$current = Read-CloudBackupAgent (Get-CloudBackupInstallation)
if (!$current -or $current.Build -ne $agent.Build) { throw 'The installed agent changed during download.' }
if ($current.Version -ge $target) { Write-Host "Already updated to $($current.Version)."; return 0 }
if (!(Test-CloudBackupUpdateWindow $Window)) { Write-Host 'Deferred. The update window ended during download.'; return 0 }
if (Test-CloudBackupPlanRunning) { Write-Host 'Deferred. An MSP360 plan worker started during download.'; return 0 }
$setup = Start-Process -FilePath $installer -ArgumentList '/S' -WindowStyle Hidden -Wait -PassThru -ErrorAction Stop
if ($setup.ExitCode -eq 3010) { Write-Host 'MSP360 setup requires a restart to finish. Run the check again after restart.'; return 3010 }
if ($setup.ExitCode -ne 0) { throw "MSP360 setup returned exit code $($setup.ExitCode)." }
$updated = Read-CloudBackupAgent (Get-CloudBackupInstallation)
if (!$updated -or $updated.Build -ne $agent.Build -or $updated.Version -lt $target) {
throw "Setup exited successfully but the installed $($agent.Build) agent could not be verified at $target or newer."
}
$service = Get-Service -Name $updated.Service -ErrorAction Stop
$service.WaitForStatus('Running', [timespan]::FromSeconds(60))
Write-Host "Updated MSP360 $($updated.Build) from $($agent.Version) to $($updated.Version). $($updated.Service) is running."
return 0
} finally {
if (Test-Path -LiteralPath $installer) { Remove-Item -LiteralPath $installer -Force -ErrorAction Stop }
}
}
$ErrorActionPreference = 'Stop'
$updateLock = New-Object -TypeName System.Threading.Mutex -ArgumentList $false,'Global\EmberkomCloudBackupUpdate'
$ownsLock = $false
try {
try { $ownsLock = $updateLock.WaitOne(0) }
catch [Threading.AbandonedMutexException] { $ownsLock = $true }
if (!$ownsLock) { Write-Host 'Deferred. Another Emberkom Cloud Backup update check is running.'; exit 0 }
$windowInput = Get-Variable -Name MSP360UpdateWindow -ErrorAction SilentlyContinue
exit (Invoke-CloudBackupUpdate -Window ([string]$windowInput.Value))
} catch {
Microsoft.PowerShell.Utility\Write-Error "Emberkom Cloud Backup update failed. $($_.Exception.Message)" -ErrorAction Continue
exit 1
} finally {
if ($ownsLock) { $updateLock.ReleaseMutex() }
$updateLock.Dispose()
}
+25
View File
@@ -0,0 +1,25 @@
# Updating Emberkom Cloud Backup between plans
Publish the repository changes to the live `master` branch, then upload [the RMM caller](../rmm/Update-EmberkomCloudBackup.ps1) to Syncro. The caller and updater require Windows PowerShell 4.0 or later. Replace any previously uploaded caller that still declares 5.1. PowerShell checks that declaration before the caller can fetch the live scripts. Run it as SYSTEM on endpoints with Emberkom Cloud Backup. Schedule it in a gap long enough for the download, installation, and backup service restart. Include restore plans and consistency checks when choosing that gap.
For endpoints that might receive a delayed RMM job, configure the optional **string** variable `MSP360UpdateWindow`. For example, `12:00-13:00` admits installation starts from noon until just before 1 p.m. in the endpoint's local time. Overnight windows such as `23:30-00:30` also work. With an omitted or blank value, Syncro controls the timing. Allow enough time after the last permitted start for setup to finish.
On each daily run, the updater reads the installed executable's file version and fetches the small release file once. If the installed version is at least as new as both published builds, it immediately reports **No update needed** and returns success (exit code 0). If either build might be newer, it asks the agent for its edition and compares the matching build.
Only a newer matching build triggers a plan check and installer download. Immediately before launching setup, the updater checks again for MSP360's `CBBackupPlan.exe` worker. A busy endpoint defers to the next scheduled run. A plan can still start after the final check, so keep the RMM slot clear of scheduled plans. [MSP360 plan worker documentation](https://help.mspbackups.com/troubleshooting)
The installer download uses a 240-second request timeout and retries once after a timeout or transient network failure. Syncro reports the endpoint name, UTC start time, source hostname, temporary installer path and expected SHA-256. For a failed network attempt, it also reports the reason, elapsed time and bytes saved. An endpoint security provider can use these details to look for a matching event. If both attempts time out, check outbound HTTPS from the endpoint under SYSTEM to the console download host and the redirected storage host. The Windows 8.7.1.177 link redirects from `console.msp360.com` to `s3.us-east-1.amazonaws.com`.
**Syncro output and exit codes**
| Code | Meaning |
| --- | --- |
| 0 | Update verified, version already current or newer, agent absent, or run deferred. The output gives the outcome. |
| 1 | Update failed. The output identifies the failed check or installer exit code. |
| 3010 | Setup requested a restart. Recheck after the endpoint restarts. |
MSP360 also checks for updates at the start of plans when its console policy allows it. To make Syncro the sole update path on selected computers, use **Downloads → Options → Exclude from auto-update** in MSP360 after the RMM job is in service. Review the scope because this console setting also covers the MSP360 RMM Agent. [MSP360 agent update policy](https://help.mspbackups.com/downloads/agent-update)
## Publishing a build
Both the existing installer and the updater read [the shared release file](../resources/EmberkomCloudBackup.json). When approving a new public build, update its four-part version, console download URL, and SHA-256 in the corresponding `Windows` or `VM` entry. Take the version from the published build and compute the hash from that exact installer using `Get-FileHash -Algorithm SHA256`. Publish the three values together. The generated setup executables can have empty Windows file-version fields.
+56 -24
View File
@@ -6,7 +6,7 @@ The selection identifies the client's purchased subscription; it does not discov
## Publish and configure ## Publish and configure
1. Publish `Install-MicrosoftOffice365.ps1` and `resources/office/Office-UserCleanup.ps1` together in the public repository. The installer requires helper version `EmberkomOfficeUserCleanup-v4`, which handles per-user Teams add-ins advertised in HKLM and protects reinstalled apps from deferred cleanup. The existing `Tools.ps1` is used unchanged. Nothing in this change publishes itself. 1. Publish `Install-MicrosoftOffice365.ps1` and `resources/office/Office-UserCleanup.ps1` together in the public repository. The installer requires helper version `EmberkomOfficeUserCleanup-v5`, which runs from memory and uses ProgramData only for synchronization state. The existing `Tools.ps1` is used unchanged. Nothing in this change publishes itself.
2. Paste/upload **rmm/Install-MicrosoftOffice365.ps1** as the Syncro **Windows PowerShell 5.1** script. Select **Run As: System** and set the execution limit to **120 minutes (2 hours)**. PowerShell 7 is not required or launched. Allow enough disk space for both the download and installation. A clean deployment downloads several GB per endpoint and requires internet access throughout companion app installation. Syncro's limit covers the entire run, including downloads, cleanup, and installation. 2. Paste/upload **rmm/Install-MicrosoftOffice365.ps1** as the Syncro **Windows PowerShell 5.1** script. Select **Run As: System** and set the execution limit to **120 minutes (2 hours)**. PowerShell 7 is not required or launched. Allow enough disk space for both the download and installation. A clean deployment downloads several GB per endpoint and requires internet access throughout companion app installation. Syncro's limit covers the entire run, including downloads, cleanup, and installation.
3. Use **Add Script Variable**, type **Dropdown**, then **Edit Dropdown Values** for each variable below. Enter names without `$`. Syncro stores dropdown definitions separately; uploading a `.ps1` does not create them. See [Syncro's script editor documentation](https://docs.syncrosecure.com/scripting-apis/manage-scripts). 3. Use **Add Script Variable**, type **Dropdown**, then **Edit Dropdown Values** for each variable below. Enter names without `$`. Syncro stores dropdown definitions separately; uploading a `.ps1` does not create them. See [Syncro's script editor documentation](https://docs.syncrosecure.com/scripting-apis/manage-scripts).
4. First run with `ValidateBeforeChanges=true` and review the result. To deploy, rerun with `false` during the maintenance window. Pilot on a disposable VM with representative Office, user profiles, and companion apps. Then run against the intended endpoint or asset selection. Group endpoints by subscription and architecture so each run's selections apply correctly. 4. First run with `ValidateBeforeChanges=true` and review the result. To deploy, rerun with `false` during the maintenance window. Pilot on a disposable VM with representative Office, user profiles, and companion apps. Then run against the intended endpoint or asset selection. Group endpoints by subscription and architecture so each run's selections apply correctly.
@@ -23,7 +23,7 @@ The selection identifies the client's purchased subscription; it does not discov
All variables configured in Syncro must have a nonempty value. Set the dropdown defaults above in Syncro; the shim reads the injected strings without assigning over them. `Select a subscription` is a nonempty placeholder that the main script rejects before deployment. All variables configured in Syncro must have a nonempty value. Set the dropdown defaults above in Syncro; the shim reads the injected strings without assigning over them. `Select a subscription` is a nonempty placeholder that the main script rejects before deployment.
`ValidateBeforeChanges` uses the existing `ConvertTo-RmmBoolean` helper from `Tools.ps1`. Missing, null, or blank input defaults to `true`; invalid text fails. The workload requires a parsed Boolean, preventing an omitted or unparsed value from enabling changes. `false` still performs prerequisite and download validation before cleanup. It does not skip those checks. `ValidateBeforeChanges` uses the existing `ConvertTo-RmmBoolean` helper from `Tools.ps1`. Missing, null, or blank input defaults to `true`; invalid text fails. The workload requires a parsed Boolean, preventing an omitted or unparsed value from enabling changes. `false` still verifies prerequisites and fresh downloads before removing installed apps.
Syncro supplies `COMPANY` automatically with the endpoint's company name in this environment. Preserve that existing mapping; no company dropdown is needed. The shim passes it through to the main script, which includes `<AppSettings><Setup Name="Company" Value="..." /></AppSettings>` in the ODT configuration, retaining the original installer's company setting. Outside Syncro, a missing value (or `None`) omits this setting. No product key, password, or tenant credentials are needed in Syncro. Syncro supplies `COMPANY` automatically with the endpoint's company name in this environment. Preserve that existing mapping; no company dropdown is needed. The shim passes it through to the main script, which includes `<AppSettings><Setup Name="Company" Value="..." /></AppSettings>` in the ODT configuration, retaining the original installer's company setting. Outside Syncro, a missing value (or `None`) omits this setting. No product key, password, or tenant credentials are needed in Syncro.
@@ -60,19 +60,21 @@ Business Basic, E1, frontline/web-only plans, education/government variants, con
## Download, removal, and installation ## 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, free space, writable paths, and HTTP availability. It returns `ValidationPassed` with the deployment plan, existing Office inventory, Click-to-Run state, running apps, `WritablePaths` and `DownloadChecks`. It creates no deployment directory and downloads no response bodies, release metadata or installation files. It does not clean old artifacts, close apps, uninstall, clear 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. Assessment sends HTTP HEAD requests, follows redirects, and requires status 200 for the ODT discovery page, helper, conditional Get Help recovery download, selected channel's Office CDN manifest, selected companion installer links, and Windows 10 release-history page when applicable. A refused HEAD request fails assessment; there is no GET fallback. The current versioned ODT executable URL and exact Windows 10 build require reading metadata, so those are resolved only in deployment mode. `OfficeVersion` is empty, `MetadataResolved=false`, `Workspace` is null and `MediaDownloaded=false`. HEAD success does not prove payload integrity, future installation or activation. The normal Tools/core bootstrap still loads live, and the normal Tools log is written. Writable-path checks create a zero-byte delete-on-close probe in the nearest existing parent of staging, ProgramData state, and Program Files paths; they leave no probe or deployment folder behind.
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 script checks prerequisites, retires previous idle user cleanup tasks, removes previous deployment artifacts while preserving logs, checks available space, and creates a fresh protected workspace. It downloads and verifies the full Office payload and selected bootstrappers, rechecks free space and running apps, performs removal/installation, verifies results, and removes all non-log staging files in `finally`. Download failures occur before installed apps are removed. An active prior installer/task or unsafe/locked artifact stops preparation; cached content is never a fallback.
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. Deployment clears prior staging before this check; assessment 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. 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 remains the normal removal path. Get Help is downloaded and run only for conditional recovery.** The command-line scrub is noninteractive, but it is not guaranteed to be invisible: the Get Help build observed on October 14, 2026 created an elevated PowerShell cleanup window in the logged-in user's session even with a hidden SYSTEM parent. Microsoft's documented `-HideProgress` option applies to other scenarios, not Office removal, so the script does not add it. See the [Get Help command-line reference](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-command-line-overview). Normal successful deployments and assessment runs do not download the scrubber.
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). In deployment mode, 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. 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.
@@ -95,13 +97,34 @@ A window that offers **Get Microsoft Teams (work or school)** does not by itself
Shutdown detection includes `Teams.exe`, `msteams.exe` (older personal/Windows Chat), and `ms-teams.exe`: `Abort` reports these running apps, while an actual deployment with `Force` closes them before removal. Earlier script versions omitted `msteams.exe`; this omission can leave that older process running, but does not explain a window confirmed to be running from `MSTeams\ms-teams.exe`. A sign-out/sign-in or restart can finish session/app registration changes; it is not a guaranteed fix for an unexplained sign-in screen. Shutdown detection includes `Teams.exe`, `msteams.exe` (older personal/Windows Chat), and `ms-teams.exe`: `Abort` reports these running apps, while an actual deployment with `Force` closes them before removal. Earlier script versions omitted `msteams.exe`; this omission can leave that older process running, but does not explain a window confirmed to be running from `MSTeams\ms-teams.exe`. A sign-out/sign-in or restart can finish session/app registration changes; it is not a guaranteed fix for an unexplained sign-in screen.
Removal starts with the separate targeted Appx/provisioned-package and Teams/OneDrive uninstall operations. ODT then runs `setup.exe /configure remove.xml` with `<Remove All="TRUE" />` and `<Display Level="None" AcceptEULA="TRUE" />` to remove Click-to-Run Office, Visio, and Project without installation UI. The XML honors `OfficeAppShutdown`; `Abort` does not silently become `Force`. The script waits for setup to exit and verifies that non-MSI Office registrations disappear, allowing up to five minutes for registration changes. It skips this separate pass when only MSI Office, or no Office, is detected. See the [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options). Removal starts with the separate targeted Appx/provisioned-package and Teams/OneDrive uninstall operations. For registered Click-to-Run products, ODT then runs `setup.exe /configure remove.xml` with `<Remove All="TRUE" />` and `<Display Level="None" AcceptEULA="TRUE" />` to remove Office, Visio, and Project. The XML honors `OfficeAppShutdown`; `Abort` does not silently become `Force`. The script waits for setup to exit and verifies that non-MSI Office registrations disappear, allowing up to five minutes for registration changes. When no Click-to-Run product is registered, it skips this removal pass and the scrub fallback. A surviving ClickToRunSvc or servicing registry key does not establish an installed product. See the [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options).
Before replacement, `Assert-OfficeRemovalComplete` requires no active installer/removal workers and no registered Click-to-Run products. It logs remaining source references and working-configuration markers as diagnostics. It no longer requires Microsoft's internal registry metadata to disappear: successful local-media installations can retain source paths, and metadata alone does not prove an operation is active. Unreadable process/product/registry state still stops deployment. Fresh media is enforced by clearing prior run downloads, creating a unique workspace, and generating this run's SourcePath; the script never deletes Microsoft's internal servicing registry/cache to force a check to pass.
Legacy MSI Office is handled by `<RemoveMSI />` in `install.xml`: ODT removes those products before installing the replacement suite in the same operation. Microsoft's [RemoveMSI guidance](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/upgrade-from-msi-version) covers Office, Visio, and Project 2007/2010/2013/2016. The script does not assume that a standalone `RemoveMSI` configuration without an installation is supported. Consequently, MSI Office can still be present during our identity/user-cleanup phase. After ODT finishes installation, the script verifies that detected MSI Office registrations are gone and the requested new product/version is installed. A completed MSI migration reports `3010` because a restart is required to finish removal, even if ODT returns zero. Legacy MSI Office is handled by `<RemoveMSI />` in `install.xml`: ODT removes those products before installing the replacement suite in the same operation. Microsoft's [RemoveMSI guidance](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/upgrade-from-msi-version) covers Office, Visio, and Project 2007/2010/2013/2016. The script does not assume that a standalone `RemoveMSI` configuration without an installation is supported. Consequently, MSI Office can still be present during our identity/user-cleanup phase. After ODT finishes installation, the script verifies that detected MSI Office registrations are gone and the requested new product/version is installed. A completed MSI migration reports `3010` because a restart is required to finish removal, even if ODT returns zero.
This is a supported uninstall and reinstall with our targeted Office identity cleanup, rather than a deep scrub of every Office artifact. A failed ODT removal or remaining non-MSI Office stops before replacement installation; remaining MSI Office after `RemoveMSI` fails the deployment even if the new suite has already installed. The error reports the remaining products and links to [Microsoft's attended scrub guidance](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall). Get Help is never an automatic fallback. Corrupt, unsupported, orphaned, or unusually packaged installations may require that repair. A removal restart result follows `DeferReboot` as described above; no automatic reboot or resume task is created. A deployment already running an older script continues using that downloaded code: let it finish before starting a new deployment. Automatic recovery is limited to **one Get Help Office scrub per deployment**, before replacement installation begins. It is selected only for these conditions:
The former Get Help 30-minute background-wait cutoff has been removed with the scrubber. Native installer processes, including ODT download/removal/installation, are awaited until they exit; there is no separate 30-minute installer cutoff. Syncro's two-hour limit remains the overall limit and is not reset between phases. Main-script registration checks now allow five minutes instead of one. Waiting for active user cleanup and its reinstall-transition lock allows 20 minutes instead of five; the per-user scheduled task limit is 30 minutes instead of 15. Those tasks may also run later for absent users. These allowances improve tolerance for slow operations but do not guarantee every endpoint finishes within two hours. If the RMM terminates a run, check for surviving installer processes before rerunning; the script does not kill an active installer to meet a time budget. - ODT removal exits `17002` or `17004`, a current native log entry identifies `InvalidDirectory` in `REMOVEINSTALLATION`, and Click-to-Run products remain registered. If products are gone and workers have finished, skip the scrub and report `3010`; `DeferReboot` controls whether installation continues. Historical entries, generic exit-code wrappers and download failures do not qualify.
- ODT exits zero, but non-MSI Office registrations remain after the bounded verification wait.
Service presence, working markers, and deployment source references alone never select removal or scrub recovery.
Recovery downloads a fresh package from Microsoft's evergreen Get Help link into this run's workspace and validates ZIP paths and the executable's Microsoft signature. Only after recovery is selected, it runs `GetHelpCmd.exe -?` and validates the downloaded tool's own usage. It invokes `-S OfficeScrubScenario -AcceptEula`, adding `-OfficeVersion All` only when that switch is advertised. This restores the earlier scrubber's runtime argument detection; observed builds reject the documented optional switch while returning zero. Usage and removal output are logged separately. The scenario must remove all detected Office registrations, including MSI Office, Visio and Project. It does not retry the scrub.
Logs include the trigger, native evidence where available, process result, and scenario result. The management log records stdout/stderr byte counts and bounded beginning/end excerpts; original stream logs retain full output. Get Help must return `0` or `3010` with numbered result `00` or `Scenario completed successfully.`; explicit error text, usage errors, contradictory results and `66`/`68` not-found results stop installation. Every accepted response still requires workers to finish, all detected Office registrations to disappear, and no installer/removal workers to remain. Read/verification failures stop deployment. The `gethelp-usage.*.log` and `office-scrub.*.log` files survive cleanup; downloaded non-log files are removed by the same guarded `finally` cleanup as other media.
When Get Help reports `Uninstall office is running in the background.`, the script now waits instead of failing immediately. It restores the earlier **30-minute background wait** and **60-second quiet interval**. Baseline process identities exclude pre-existing unrelated consoles; newly launched script/installer workers and explicitly identified scrub workers block completion. At least one identified scrub worker must be observed. Worker disappearance alone is insufficient: the script retains process handles to verify identified workers exited with `0` or `3010`, checks all Office registrations, and requires all conditions to stay clear for the quiet interval. Failed/interrupted workers, inaccessible exit status, no observed worker, remaining products or a timeout stop installation. The overall Syncro limit still applies.
**Visible last-resort window:** Get Help may launch `powershell.exe -File ...\GetHelpElevated\<id>\Run.ps1` outside the deployment workspace and display it in a user's session. Leave it open during cleanup. The observed Microsoft launcher waits for a key in `finally` after either success or failure; dismiss a completed `Press any key to exit` prompt so verification can proceed. The window is not locked against closure. Get Help exposes no documented Office-scrub switch for that, and a handler registered in the RMM parent cannot protect another process; Windows still terminates a console process after a close signal ([console handler behavior](https://learn.microsoft.com/en-us/windows/console/handlerroutine)). The script monitors worker exit codes and endpoint state instead of modifying signed vendor scripts or injecting UI input. A successful process exit alone never proves removal. Get Help's diagnostic reports, when produced, are directly in the worker account's `%LOCALAPPDATA%\DAFs` as `cse.amplify.diagaction.gethelp.officeuninstallalda_<timestamp>.log`. Existing active workers block a new deployment; never reuse their payloads for the next run.
The wait checks fresh Get Help reports in each identified worker's account (both SYSTEM profile locations when applicable). A complete `GH_OfficeUninstallALDA` report with `ExecutionResult=Failed` stops immediately with its detail and path, even if the worker is still waiting for a key. Old reports, partial JSON, and reports for other scenarios are ignored. A report never authorizes killing the worker or skipping process/product checks. Successful scrub workers may still require the completed keypress prompt to be dismissed; fully unattended fallback is not established for that launcher. A timeout ends the deployment before installation and does not schedule automatic resume.
A verified scrub reports `3010` because Microsoft recommends a restart to finish cleanup. With `DeferReboot=true`, installation can continue after verification and the final receipt preserves the restart requirement. With `false`, the script returns `RestartRequiredBeforeInstall`. Returned Office-removal/install receipts include `ScrubRecoveryAttempted` and `ScrubRecoveryReason`. No automatic reboot or resume task is created. See [Microsoft's Office scrub guidance](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall).
Other ODT errors still stop for diagnosis. No automatic scrub is attempted after replacement installation begins, including a failed `RemoveMSI` check that could occur after the new suite is installed. A deployment already running an older script continues using that downloaded code: let it finish before starting another deployment.
Native installer processes, including ODT and the conditional scrub, are awaited using `Start-Process -Wait`; there is no separate 30-minute installer cutoff. Get Help can detach a worker beyond that wait, as described above. Syncro's two-hour limit remains the overall limit and is not reset between phases. After a terminal scrub result, verification allows five minutes for registration and background-worker state to settle. Surviving Get Help/OffScrub workers, including `GetHelpElevated\...\Run.ps1`, block installation, new deployment downloads, and artifact deletion even outside the current workspace. Waiting for active user cleanup and its reinstall-transition lock allows 20 minutes; the per-user scheduled task limit is 30 minutes. Those tasks may also run later for absent users. These allowances do not guarantee every endpoint finishes within two hours. If the RMM terminates a run, check for surviving installer processes before rerunning; the script does not kill an active installer to meet a time budget.
Transient failures get bounded recovery before deployment stops: Transient failures get bounded recovery before deployment stops:
@@ -114,6 +137,14 @@ Transient failures get bounded recovery before deployment stops:
Retries and waits are recorded in the diagnostic log. Persistent failures still stop the run with an error; these recovery paths do not turn incomplete deployment into success. Retry counts and delays are grouped in `Get-OfficeDeploymentDefinitions`; the standalone user helper has its MSI retry settings in `Get-OfficeUserCleanupDefinitions`. Retries and waits are recorded in the diagnostic log. Persistent failures still stop the run with an error; these recovery paths do not turn incomplete deployment into success. Retry counts and delays are grouped in `Get-OfficeDeploymentDefinitions`; the standalone user helper has its MSI retry settings in `Get-OfficeUserCleanupDefinitions`.
## Investigating a failed deployment without rerunning it
`Get-OfficeDeploymentDiagnostics.ps1` collects evidence without importing or executing the installer. Copy this root script to the endpoint and run it in elevated PowerShell, or publish it and use `rmm/Get-OfficeDeploymentDiagnostics.ps1` as SYSTEM. The RMM caller fetches Tools and the core live and needs no inputs. It writes a ZIP under `C:\ProgramData\Emberkom\Logs\OfficeDiagnostics` and prints the full path. No deployment folder, payload download, uninstall, repair, process termination, registry write, or task registration is performed by the collector. The normal RMM Tools bootstrap still initializes its management logs.
The ZIP includes the last 72 hours of native Office logs from Windows and user temp folders, Office-related management logs, deployment logs/configuration XML, and Get Help DAF reports across all discovered profiles. It includes the GetHelpElevated launcher/support scripts for inspection, even when their package timestamps are older. Current boot time, process owners/sessions, Click-to-Run service state, selected Office registry values from both views, installed Office entries, and Emberkom cleanup tasks are captured separately in `endpoint.json`. It excludes installation executables and media, user documents, and identity/licensing-store exports. Logs can contain user names and paths. `manifest.json` records original paths/timestamps; `collection-issues.json` records access failures and collection limits (64 MB/file, 512 MB total, 2000 files). Live files are copied with shared access and are not an atomic snapshot.
Compare timestamps inside the native logs for the failed `REMOVEINSTALLATION` and successful installation operations. Running the same staged `setup.exe /configure install.xml` successfully establishes that this media/configuration can install in the later endpoint state and execution context. It does not prove removal completed at the earlier timeout, nor establish behavior under SYSTEM. A reboot after a scrub and a reboot before a deployment that launches another scrub are different sequences. Current registry/service/process state cannot reconstruct the earlier state by itself. Preserve a now-working installation while collecting this evidence; use a disposable VM with a restored baseline for destructive comparisons.
## Identity cleanup and absent users ## Identity cleanup and absent users
The core script clears Office 15/16 identity/licensing registry keys and Office licensing token folders in each locally available non-special Windows profile, loading unloaded user hives when needed. Unavailable profiles/containers stop deployment before removal. FSLogix/roaming profiles that are not registered locally are outside this script's coverage. The core script clears Office 15/16 identity/licensing registry keys and Office licensing token folders in each locally available non-special Windows profile, loading unloaded user hives when needed. Unavailable profiles/containers stop deployment before removal. FSLogix/roaming profiles that are not registered locally are outside this script's coverage.
@@ -126,22 +157,21 @@ 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. 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 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. 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 but do no cleanup after success. An administrator can confirm completion and remove those exact tasks and their synchronization folder afterward. There is no daily housekeeping task.
If any cleanup task could not be registered, successful installation instead returns **InstalledWithUserCleanupIncomplete** with `UserCleanupRegistrationFailures` entries containing `SID`, `ProfilePath`, and `Error`. `PendingUserSids` still lists only registered tasks awaiting completion. Signing in alone cannot retry a missing task: review whether the profile belongs to a deleted account or whether account lookup/task registration needs repair. The script does not delete profiles or grant a different account access to their credentials. The machine-side Office identity/cache cleanup still runs before task registration. If any cleanup task could not be registered, successful installation instead returns **InstalledWithUserCleanupIncomplete** with `UserCleanupRegistrationFailures` entries containing `SID`, `ProfilePath`, and `Error`. `PendingUserSids` still lists only registered tasks awaiting completion. Signing in alone cannot retry a missing task: review whether the profile belongs to a deleted account or whether account lookup/task registration needs repair. The script does not delete profiles or grant a different account access to their credentials. The machine-side Office identity/cache cleanup still runs before task registration.
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. These logon tasks fetch the version-matched user helper live over HTTPS and execute it in memory; sign-in cleanup therefore requires network access to the repository. No helper script or installer is cached for them. Only the empty lock and reinstall-phase marker remain in `%ProgramData%\EmberkomOfficeDeployment\<deployment-id>` while tasks are pending. These are required synchronization state, separate from the logs-only download workspace. The receipt identifies this folder as `UserCleanupWorkspace`. If no tasks remain after a successful deployment, the folder is removed too. A new deployment retires previous idle tasks and clears their state before creating fresh tasks for the currently registered profiles; active tasks block redeployment. If preparation then fails, the retired tasks are not recreated until deployment reaches user cleanup again.
## Temporary media and cleanup during deployment ## 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. - 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 cross-run reuse of media, manifests, options or XML.
- 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. - Before creating it, deployment cleans prior GUID workspaces under execution/profile temp, Windows Temp/SystemTemp and legacy ProgramData roots. There is no minimum age. Non-GUID folders outside this managed scope are untouched.
- 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. - `finally` removes every non-log file from the current download workspace on success, failed download/install, and early restart exits. This includes payloads, bootstrappers, helper scripts, XML, options and locks. `.log` and `.etl` files and their parent directories remain. The selected options are recorded in `deployment-options.log`.
- 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. - Before deleting artifacts, cleanup rejects reparse points, inventories processes, and probes all candidate files for exclusive access. Active installers or processes referencing the workspace block cleanup. Process-inventory failures also retain the files. A new deployment stops if prior artifacts cannot be cleared safely.
- 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. - Receipts include `ArtifactCleanupPending=true` when cleanup fails. An otherwise clean install then returns exit `2` and `InstalledWithArtifactCleanupPending`; existing errors, partial-user-cleanup statuses and required-restart results remain intact. The original installation exception is never replaced by a cleanup error.
- 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. - Pending logon tasks retain only their separate synchronization state, as described above. No downloaded code or media is intentionally retained for them.
- Hard RMM termination or power loss can bypass `finally`. The next deployment clears the abandoned artifacts before downloading anything new. No scheduled housekeeping job is created. `Start-SystemCleanup.ps1` retains its separate conservative, age-based cleanup behavior for legacy workspaces; it is not required before redeployment.
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 ## Results and troubleshooting
@@ -149,7 +179,7 @@ Earlier ProgramData caches are not searched for reuse in the new temp location.
| --- | --- | | --- | --- |
| `0` | `ValidationPassed`: validation only, no deployment performed. `Installed`: Office and companion installations verified; user cleanup completed for the enumerated profiles. | | `0` | `ValidationPassed`: validation only, no deployment performed. `Installed`: Office and companion installations verified; user cleanup completed for the enumerated profiles. |
| `1` | Failure; inspect the error and logs. In deployment mode, removal may already have happened. | | `1` | Failure; inspect the error and logs. In deployment mode, removal may already have happened. |
| `2` | Office and companion apps installed, but user cleanup is pending or incomplete. `InstalledWithUserCleanupPending`: sign in as the listed `PendingUserSids` and inspect task results. `InstalledWithUserCleanupIncomplete`: also review `UserCleanupRegistrationFailures`; those users do not have a registered cleanup task. Do not repeatedly reinstall merely to check status. | | `2` | Installation completed with pending work: `InstalledWithUserCleanupPending` lists users needing sign-in; `InstalledWithUserCleanupIncomplete` lists task-registration failures; `InstalledWithArtifactCleanupPending` indicates artifacts could not be removed safely. Inspect the receipt and logs. Do not repeatedly reinstall merely to check status. |
| `3010` | A restart is required. Read `OfficeDeploymentStatus`: `RestartRequiredBeforeInstall` means restart then rerun; any `Installed*` status means Office and companions completed with a restart deferred until afterward. `RestartRequired=true` and `DeferReboot` are included; a stop before installation also identifies `RestartStage`. Pending user SIDs and task registration failures can also be present. | | `3010` | A restart is required. Read `OfficeDeploymentStatus`: `RestartRequiredBeforeInstall` means restart then rerun; any `Installed*` status means Office and companions completed with a restart deferred until afterward. `RestartRequired=true` and `DeferReboot` are included; a stop before installation also identifies `RestartStage`. Pending user SIDs and task registration failures can also be present. |
Syncro may flag nonzero results as errors; read the printed status, pending SIDs, and task registration failures. Schedule any required restart separately. The script also returns `3010` after verified legacy MSI Office removal, following Microsoft's restart requirement. Syncro may flag nonzero results as errors; read the printed status, pending SIDs, and task registration failures. Schedule any required restart separately. The script also returns `3010` after verified legacy MSI Office removal, following Microsoft's restart requirement.
@@ -162,7 +192,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. 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 and `deployment-options.log` remain in the reported `Workspace`. Generated `remove.xml` and `install.xml` are deleted along with downloaded content after each attempt; assessment creates no workspace. ODT removal logs are `office-remove.stdout.log` / `.stderr.log`; installation logs are `office-install.stdout.log` / `.stderr.log`. The main Tools log retains the actions, results, and receipt and is not deleted. The separate limited-user cleanup task writes its transcript in `%LOCALAPPDATA%\Emberkom\OfficeDeployment\<deployment-id>.log`. Do not manually delete `UserCleanupWorkspace` synchronization state 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 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,10 +200,12 @@ The installer verifies the selected Office product, bitness, and downloaded vers
## Verification ## 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 in Windows PowerShell 5.1. Coverage includes HEAD-only assessment and status failures, temporary write probes, no metadata/staging/housekeeping during assessment, prior-run cleanup with nested-log preservation, active-process/task and locked-file protection, live user-helper execution, orphaned Click-to-Run removal and stale-state rejection. Recovery checks cover the observed InvalidDirectory error, exclusion of stale/unrelated evidence, ZIP containment, signature failures, one-attempt enforcement, ambiguous/failed/not-found scrub results, zero-exit argument/usage errors, bounded stream excerpts without changing parser input, surviving workers, all-product removal verification, log preservation and both restart policies. Existing checks cover strings through the real shim/Tools loader, exit-code propagation, native-host relaunch, deployment order, companion verification, retries and identity cleanup boundaries. Tests mock downloads and disruptive actions; they do not run Microsoft installers, change actual registry state, or clear 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. `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.
Restored scrub tests cover advertised/unsupported arguments, both result formats, background acknowledgement, delayed inventory, a restarted quiet interval, a worker left at the keypress prompt, closed/failed workers, unknown worker identity, missing observed workers, stale state, and the 30-minute bound. An inert PowerShell child verifies that the retained process handle preserves a nonzero exit code after the child terminates. No actual scrubber is executed by the suite.
Endpoint acceptance still requires a VM pilot: existing MSI/C2R/Store Office, machine/per-user Teams and OneDrive, a logged-off profile, standard-user sign-in, wrong-license rejection, download failure, and the restart path. Verify new Outlook and Teams registration at sign-in, OneDrive migration, and that delayed cleanup preserves reinstalled apps. The implementation has not been run destructively against a real endpoint during development. Endpoint acceptance still requires a VM pilot: existing MSI/C2R/Store Office, machine/per-user Teams and OneDrive, a logged-off profile, standard-user sign-in, wrong-license rejection, download failure, and the restart path. Verify new Outlook and Teams registration at sign-in, OneDrive migration, and that delayed cleanup preserves reinstalled apps. The implementation has not been run destructively against a real endpoint during development.
## Maintaining deployment definitions ## Maintaining deployment definitions
+93 -14
View File
@@ -30,8 +30,9 @@ use. The core does not need to download Tools.ps1 itself.
Run once with `CleanupReportOnly=true`, then set it to `false` to apply. Report Run once with `CleanupReportOnly=true`, then set it to `false` to apply. Report
mode assesses **all categories regardless of their enablement**, using the current mode assesses **all categories regardless of their enablement**, using the current
retention settings. It leaves the enablement variables unchanged. The final report retention settings. It leaves the enablement variables unchanged. The compact
has three sections: report starts with the unique enabled savings and additional disabled savings,
followed by a component-store note, then every category once in three sections:
- **Enabled:** eligible for cleanup on an apply run, subject to the reported conditions. - **Enabled:** eligible for cleanup on an apply run, subject to the reported conditions.
- **Disabled:** potential savings only; these categories will not run during apply - **Disabled:** potential savings only; these categories will not run during apply
@@ -47,21 +48,69 @@ File categories report their independent eligible file counts and logical bytes.
These category estimates can overlap (for example, a duplicate downloaded EXE). These category estimates can overlap (for example, a duplicate downloaded EXE).
The enabled total counts each file path once. The disabled total shows additional The enabled total counts each file path once. The disabled total shows additional
unique file bytes beyond those already counted in enabled categories. Native unique file bytes beyond those already counted in enabled categories. Native
operations such as Disk Cleanup, VSS, Search compaction, Delivery Optimization, operations such as Disk Cleanup, Search compaction, Delivery Optimization,
component cleanup, and disabling hibernation say **not estimated**, not zero. and component cleanup show `-` and **not estimated**, not
Disk Cleanup also lists its preset (or custom list), expanded selected handlers, zero. Disk Cleanup shows its preset (or Custom) and selected handler count.
and unselected handlers without running them. `None` places Disk Cleanup in the `None` places Disk Cleanup in the Disabled section. Servers always place it in
Disabled section; the report still lists the unselected handlers. Servers always the Blocked section, regardless of the preset.
place it in the Blocked section, regardless of the preset.
Skipped/unavailable categories say **not assessed**; failed or partially assessed Skipped/unavailable categories say **not assessed**; failed or partially assessed
categories are labeled incomplete. In-use application checks remain enforced, so categories are labeled incomplete. In-use application checks remain enforced, so
close those applications and rerun to obtain their estimates. Unknown savings are close those applications and rerun to obtain their estimates. Unknown savings are
excluded from the totals, and file sizes do not guarantee physical space savings. excluded from the totals, and file sizes do not guarantee physical space savings.
Report mode does not delete files, change registry settings, stop services, The report-only diagnostics run regardless of the corresponding cleanup flags:
launch maintenance programs, or request scheduled maintenance. Acquiring a named
mutex prevents overlapping runs; the RMM bootstrap still downloads Tools/core - **DisableHibernation:** the category's MiB column shows the current system-drive
and may produce its usual logs. Native cleanup savings cannot be estimated. `hiberfil.sys` size, or `0.00` when absent. Its note identifies this as file size.
- **ShadowCopies:** the category's MiB column shows used shadow storage for the
system volume, or `0.00` when no storage association exists. Its note identifies
VSS usage and the drive where the data resides. Storage on another drive is
labeled accordingly; it does not represent space occupied on C:. Allocation
details remain available in verbose output.
- **ComponentStore:** a short note that removing superseded updates may free
substantial space, or little/none. The component store is not analyzed, and no
Yes/No recommendation or package count is calculated. The note appears even if
`CleanupComponentStore=false` or `CleanupDiskCleanupItems=None`.
There are no separate Hibernation or ShadowStorage diagnostic lines. The two
native rows keep `-` in the Files column. Failed/unsupported inspections show `-`
for MiB and **unavailable**, never zero. Structured results expose these usage
measurements as `UsageBytes`, separately from `CandidateBytes`.
These are **current usage and potential, not extra reclaimable bytes**;
they are excluded from both savings totals. VSS data may be shared between
snapshots, and the script retains the newest snapshot. Hibernation/VSS diagnostics
remain unassessed on servers under the existing server policy. The component-store
note appears on both clients and servers. Diagnostics are skipped in
apply mode and require no new Syncro variables.
Report mode does not launch DISM analysis, avoiding its additional runtime on slow
endpoints. Component cleanup removes superseded updates, so potential savings
depend on accumulated updates and previous Windows maintenance. A large WinSxS
folder alone does not indicate how much is reclaimable. Actual cleanup still uses
the existing background task when `CleanupComponentStore=true` in apply mode.
The default output is designed for Syncro's limited script output: one line per
category, including zero results, without a second PowerShell object dump or
per-category progress chatter. Column sizes are in MiB; positive sizes below
0.01 MiB display as `<0.01`. The group identifies whether a category is enabled;
its variable is `Cleanup<Category>`, except Disk Cleanup uses
`CleanupDiskCleanupItems`. Skip, failure, and partial-assessment reasons remain
visible. Long diagnostic notes are shortened to one line.
To troubleshoot, set `$VerbosePreference = 'Continue'` in the caller before
`Run-Script`. Verbose output includes progress, full diagnostic notes, and the
selected/unselected Disk Cleanup handler lists; it can exceed Syncro's output
limit, so use a local PowerShell capture when full detail is needed. No additional
Syncro variable is required. The `Invoke-SystemCleanup` function still returns
structured results for programmatic callers; the script entry suppresses their
automatic formatting after printing the human-readable report.
Report mode performs no cleanup, changes no cleanup registry settings, stops no
services, launches no native programs, and requests no scheduled maintenance.
Acquiring a named mutex prevents overlapping
runs; the RMM bootstrap still downloads Tools/core and may produce its usual logs.
Native cleanup savings cannot be estimated from these usage measurements alone.
Boolean options accept native booleans or true/false, yes/no, 1/0 strings. Blank Boolean options accept native booleans or true/false, yes/no, 1/0 strings. Blank
or unrecognized boolean values fail before cleanup. Retention values must be or unrecognized boolean values fail before cleanup. Retention values must be
@@ -71,10 +120,11 @@ selections, and mixtures of presets with other values also fail before cleanup.
| Variable | Default | Purpose | | Variable | Default | Purpose |
| --- | --- | --- | | --- | --- | --- |
| `CleanupReportOnly` | true | Assess all categories versus apply enabled categories only | | `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 | | `CleanupDiagnosticDays` | 30 | CBS, WER archives, dumps, Revit journals |
| `CleanupBackupDays` | 30 | Downloads, backups, time spent in Recycle Bin | | `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 | | `CleanupUserTemp` | true | Registered user profiles' Local Temp; AutoCAD `.ac$` only with AutoCAD closed |
| `CleanupServiceTemp` | true | LocalService, NetworkService, SYSTEM profile temp folders | | `CleanupServiceTemp` | true | LocalService, NetworkService, SYSTEM profile temp folders |
| `CleanupCBSArchives` | true | `CbsPersist_*.log` and `CbsPersist_*.cab` | | `CleanupCBSArchives` | true | `CbsPersist_*.log` and `CbsPersist_*.cab` |
@@ -169,6 +219,22 @@ termination can leave a temporary slot behind; future runs skip occupied slots.
## Deletion and operational boundaries ## 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 - Inspect each file's modification time; an old parent never authorizes deletion
of newer children. Ordinary cache/temp directories are retained. of newer children. Ordinary cache/temp directories are retained.
- Use literal local paths, verify containment, and skip reparse points and linked - Use literal local paths, verify containment, and skip reparse points and linked
@@ -213,8 +279,21 @@ Coverage includes disabled-category estimates, separate report groups, unique
totals for overlapping categories, and disabled categories remaining untouched in totals for overlapping categories, and disabled categories remaining untouched in
apply mode. Preset tests verify exact handler membership, cumulative selections, apply mode. Preset tests verify exact handler membership, cumulative selections,
RMM scope preservation, None disabling native work, and the server exclusions. RMM scope preservation, None disabling native work, and the server exclusions.
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), 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), [Disk Cleanup](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cleanmgr),
[component cleanup](https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/clean-up-the-winsxs-folder), [component cleanup](https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/clean-up-the-winsxs-folder),
[component analysis](https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/determine-the-actual-size-of-the-winsxs-folder?view=windows-11),
[shadow-storage measurements](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/vsswmi/win32-shadowstorage),
[Windows Search](https://learn.microsoft.com/troubleshoot/windows-client/shell-experience/windows-search-performance-issues). [Windows Search](https://learn.microsoft.com/troubleshoot/windows-client/shell-experience/windows-search-performance-issues).
+12
View File
@@ -0,0 +1,12 @@
{
"Windows": {
"Version": "8.7.1.177",
"Url": "https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWTBzNG1zVDV0ckVMdStZVzBsam5uZklMVnZLeTBMVmxGNWt4VDhSMzNIL3VmK3VHNmxBVEZTQkxhMFhNR2ZuZzJCeE80MDJxVkRSWXdNa0dqSHdpbUN1bE01c3BWNFBVUmt2Q1c4endncjVZemFSSjEyYmFNL3hESHR2eWpVYXpBVlV2eU1kZVZFaEpvalk2Rk40Wk96UG9QdUwxYnZrRHREMmhLeTZoMW5Rbz0*&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4",
"SHA256": "1EC7E1FAF23DE3D5C23BC147823D8A41A7A75B631E5E041EDEDF0A76233BF2FE"
},
"VM": {
"Version": "8.7.1.177",
"Url": "https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWUpYM2xDY3ErMkpOVGpuWTRISDNFcFRFdWRibDgvTm8vUDhpWndON3kzaHNwOTFVa3h6WUdoeVVod1JmT2lRQ1FlVTE3Y0pnUncwSEJwS3FFcDBmTWt3cEdnSy9YemRsSTRiQWJHNi96cUtWbzZsc25QVllaR1QyQ21VVS95dFFVTkNndXdPVStGQXBIT0FZb2FIUzFuZy9mMU5qZUd5emhab1hFYjZWODB4ND0*&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4",
"SHA256": "F247D73C30CCE522FDE6FCEB0F00984BB88D0010D657BC379A673BACAD32F804"
}
}
+5 -3
View File
@@ -1,6 +1,6 @@
#Requires -Version 5.1 #Requires -Version 5.1
# EmberkomOfficeUserCleanup-v4 # EmberkomOfficeUserCleanup-v5
# Run only as the affected user, at limited privilege; staged by the Office installer. # Run only as the affected user, at limited privilege; fetched live by its logon task.
param([Parameter(Mandatory = $true)][ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId) param([Parameter(Mandatory = $true)][ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId)
function Get-OfficeUserCleanupDefinitions { function Get-OfficeUserCleanupDefinitions {
@@ -184,7 +184,9 @@ $null = Start-Transcript -Path (Join-Path $logFolder "$DeploymentId.log") -Appen
try { try {
$null = New-Item -Path $marker -Force $null = New-Item -Path $marker -Force
Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Running' Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Running'
Invoke-OfficeUserCleanup -Workspace $PSScriptRoot # The scheduled action fetches this helper live into memory. Only protected
# synchronization state persists on disk; PSScriptRoot is empty in this mode.
Invoke-OfficeUserCleanup -Workspace (Join-Path $env:ProgramData "EmberkomOfficeDeployment\$DeploymentId")
Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Complete' Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Complete'
} catch { } catch {
Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Failed' Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Failed'
+8
View File
@@ -0,0 +1,8 @@
#Requires -Version 5.1
# Run as SYSTEM. Collects the last 72 hours of Office logs and current state into
# ProgramData\Emberkom\Logs\OfficeDiagnostics. No operator inputs are required.
# Does not install, uninstall, close apps, or launch the deployment script.
$ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
. $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1')))
Run-Script -LivePSScript Get-OfficeDeploymentDiagnostics
+2 -1
View File
@@ -1,3 +1,4 @@
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
. $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1'))) . $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1')))
# Set the edition of the ECB agent. # Set the edition of the ECB agent.
@@ -9,4 +10,4 @@ $MSP360Username = '{[MSP360_Username]}'
$MSP360Password = '{[MSP360_Password]}' $MSP360Password = '{[MSP360_Password]}'
# Run the installation script # Run the installation script
Run-Script -LivePSScript Install-EmberkomCloudBackup Run-Script -LivePSScript Install-EmberkomCloudBackup
+9
View File
@@ -4,6 +4,15 @@
# See docs/Office365-Deployment.md. # See docs/Office365-Deployment.md.
# Configure these [string] Dropdown variables in Syncro: # Configure these [string] Dropdown variables in Syncro:
# [string]$ValidateBeforeChanges - true (default: validate only), false (remove/reinstall) # [string]$ValidateBeforeChanges - true (default: validate only), false (remove/reinstall)
# Assessment checks writable paths and HTTP HEAD 200; it creates no deployment directory or downloads.
# Deployment clears prior run artifacts, downloads fresh media before uninstalling, and leaves only logs.
# Only registered Click-to-Run products require removal; service/registry remnants alone do not.
# Failed removal with products remaining can trigger one Microsoft Get Help scrub.
# Scrub downloads are on demand, may display a child window, and honor DeferReboot after verification.
# Background scrub waits up to 30 minutes plus verification within Syncro's overall limit.
# Leave its window open during removal; dismiss a completed 'Press any key to exit' prompt.
# The child window cannot be reliably locked; failed/interrupted monitored workers stop installation.
# Pending user tasks keep synchronization markers and fetch their helper live. Active installers block cleanup.
# [string]$OfficeSubscription - Required; use the exact subscription names in the guide. # [string]$OfficeSubscription - Required; use the exact subscription names in the guide.
# [string]$OfficeArchitecture - Auto (default), 64, 32 # [string]$OfficeArchitecture - Auto (default), 64, 32
# [string]$UpdateChannel - Current (default), MonthlyEnterprise, SemiAnnual # [string]$UpdateChannel - Current (default), MonthlyEnterprise, SemiAnnual
+10
View File
@@ -2,6 +2,7 @@
# Configure these [string] Dropdown variables in Syncro, each with true/false choices: # Configure these [string] Dropdown variables in Syncro, each with true/false choices:
# [string]$CleanupReportOnly - true (default: assess all), false (apply enabled only) # [string]$CleanupReportOnly - true (default: assess all), false (apply enabled only)
# [string]$CleanupSystemTemp - true (default), false # [string]$CleanupSystemTemp - true (default), false
# [string]$CleanupOfficeStaging - true (default), false; uses CleanupTempDays
# [string]$CleanupUserTemp - true (default), false # [string]$CleanupUserTemp - true (default), false
# [string]$CleanupServiceTemp - true (default), false # [string]$CleanupServiceTemp - true (default), false
# [string]$CleanupCBSArchives - true (default), false # [string]$CleanupCBSArchives - true (default), false
@@ -39,8 +40,17 @@
# The main script parses the injected strings and supplies defaults for absent variables. # The main script parses the injected strings and supplies defaults for absent variables.
# Every variable configured in Syncro needs a nonempty value. # Every variable configured in Syncro needs a nonempty value.
# Report-only assesses enabled AND disabled categories in separate report sections. # Report-only assesses enabled AND disabled categories in separate report sections.
# Compact output shows totals first and one row per category; no duplicate object dump.
# Hibernation/VSS usage appears in the category MiB column (0.00 if absent).
# Report-only also notes potential component-store savings without estimating them.
# Usage is excluded from savings. Hibernation/VSS remain unassessed on servers.
# Reports do not run DISM analysis; savings from superseded updates are not estimated.
# For full diagnostics, set $VerbosePreference = 'Continue' before Run-Script.
# 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-blocked categories are listed without assessment. Native savings may be unknown.
# Server exclusions cannot be overridden by these variables. No reboot is initiated. # 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' $ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+9
View File
@@ -0,0 +1,9 @@
#Requires -Version 4.0
# Syncro: run as SYSTEM at a time reserved between backup, restore and consistency plans.
# Optional string $MSP360UpdateWindow, e.g. '12:00-13:00' in endpoint local time.
# Leave blank to use the Syncro schedule alone. See docs/EmberkomCloudBackup-Updates.md.
$ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
. $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1')))
Run-Script -LivePSScript Update-EmberkomCloudBackup
exit $LASTEXITCODE
@@ -0,0 +1,129 @@
#Requires -Version 5.1
$ErrorActionPreference = 'Stop'
if ($PSVersionTable.PSEdition -ne 'Desktop') { throw 'Run with Windows PowerShell 5.1.' }
$repo = Split-Path -Parent $PSScriptRoot
$testRoot = Join-Path $env:TEMP ('OfficeDiagnosticsTests-' + [guid]::NewGuid().ToString('N'))
$originalTemp = [IO.Path]::GetFullPath($env:TEMP).TrimEnd('\') + '\'
$nativePowerShell = Join-Path $env:windir 'System32\WindowsPowerShell\v1.0\powershell.exe'
$null = New-Item -ItemType Directory -Path $testRoot
$script:assertions = 0
function Assert-DiagnosticTest { param([bool]$Condition, [string]$Message) $script:assertions++; if (!$Condition) { throw $Message } }
function Read-DiagnosticAst {
param([string]$Path)
$tokens=$null; $errors=$null
$ast=[Management.Automation.Language.Parser]::ParseFile($Path,[ref]$tokens,[ref]$errors)
if ($errors.Count) { throw ($errors | Out-String) }
$ast
}
function Read-ZipText {
param($Archive,[string]$Name)
$reader=New-Object IO.StreamReader($Archive.GetEntry($Name).Open())
try { $reader.ReadToEnd() } finally { $reader.Dispose() }
}
$savedEnvironment=@{}
try {
$coreAst=Read-DiagnosticAst (Join-Path $repo 'Get-OfficeDeploymentDiagnostics.ps1')
$shimAst=Read-DiagnosticAst (Join-Path $repo 'rmm\Get-OfficeDeploymentDiagnostics.ps1')
Assert-DiagnosticTest (!$coreAst.ParamBlock -and !$shimAst.ParamBlock) 'RMM scripts must not introduce script parameters.'
$definitions=@($coreAst.FindAll({param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst]},$false))
foreach ($definition in $definitions) { . ([scriptblock]::Create($definition.Extent.Text)) }
Add-Type -AssemblyName System.IO.Compression.FileSystem
$source=Join-Path $testRoot 'source'; $null=New-Item -ItemType Directory -Path "$source\nested\deep" -Force
[IO.File]::WriteAllText("$source\live.log",'fixture with Unicode: caf'+[char]0xE9)
[IO.File]::WriteAllText("$source\install.xml",'<Configuration />')
[IO.File]::WriteAllText("$source\media.dat",'not diagnostics')
[IO.File]::WriteAllText("$source\nested\child.log",'child log')
[IO.File]::WriteAllText("$source\nested\deep\excluded.log",'too deep')
$issues=New-Object 'Collections.Generic.List[string]'
$files=@(Get-OfficeDiagnosticFiles $source @('*.log','install.xml') ([datetime]::UtcNow.AddHours(-1)) 1 $issues)
Assert-DiagnosticTest ($files.Count -eq 3 -and !@($files | Where-Object {$_.Name -in @('media.dat','excluded.log')}).Count) 'Only requested diagnostics within the recursion depth may be collected.'
Assert-DiagnosticTest (@(Get-OfficeDiagnosticFiles $source @('*.log') ([datetime]::UtcNow.AddHours(1)) 1 $issues).Count -eq 0) 'Old files must be excluded by the time window.'
$before=(Get-FileHash -LiteralPath "$source\live.log").Hash
$held=[IO.File]::Open("$source\live.log",[IO.FileMode]::Open,[IO.FileAccess]::ReadWrite,[IO.FileShare]::ReadWrite)
try { New-OfficeDiagnosticArchive "$testRoot\fixture.zip" ($files + $files) @{CurrentStateOnly=$true} $issues }
finally { $held.Dispose() }
$zip=[IO.Compression.ZipFile]::OpenRead("$testRoot\fixture.zip")
try {
$manifest=Read-ZipText $zip 'manifest.json' | ConvertFrom-Json
Assert-DiagnosticTest ($manifest.Count -eq 3 -and @($manifest | Where-Object {$_.Status -notlike 'Captured*'}).Count -eq 0) 'Duplicate paths must be collected once, including a log open by another writer.'
$entry=@($manifest | Where-Object {$_.Source -eq "$source\live.log"})[0]
Assert-DiagnosticTest ((Read-ZipText $zip $entry.Entry) -eq [IO.File]::ReadAllText("$source\live.log")) 'Captured bytes must preserve source encoding/content.'
Assert-DiagnosticTest ($null -ne $zip.GetEntry('endpoint.json') -and $null -ne $zip.GetEntry('collection-issues.json')) 'Metadata and collection omissions must accompany the logs.'
} finally { $zip.Dispose() }
Assert-DiagnosticTest ((Get-FileHash -LiteralPath "$source\live.log").Hash -eq $before) 'Source logs must remain unchanged.'
$big=[IO.File]::Create("$source\oversize.log"); try {$big.SetLength(64MB+1)} finally {$big.Dispose()}
$issues=New-Object 'Collections.Generic.List[string]'
New-OfficeDiagnosticArchive "$testRoot\limits.zip" @((Get-Item "$source\oversize.log")) @{} $issues
Assert-DiagnosticTest ($issues.Count -eq 1 -and $issues[0] -match 'Collection limit') 'Oversize logs must be reported as omitted, not silently lost.'
# Exercise the actual Run-Script helper with mocked live downloads and queries.
# The core's registry reader is replaced only in the fixture downloaded by this test.
$toolsAst=Read-DiagnosticAst (Join-Path $repo 'Tools.ps1')
$runDefinition=$toolsAst.Find({param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Run-Script'},$false)
. ([scriptblock]::Create($runDefinition.Extent.Text))
function IsURLValid { param($URL) $true }
function Download-File { param($URL) Assert-DiagnosticTest ($URL -like '*/Get-OfficeDeploymentDiagnostics.ps1') 'Caller must request the diagnostic core.'; "$testRoot\downloaded-core.ps1" }
$fixtureCore=($definitions | Where-Object {$_.Name -ne 'Get-OfficeDiagnosticRegistry'} | ForEach-Object {$_.Extent.Text}) -join "`r`n"
$fixtureCore += "`r`nInvoke-OfficeDiagnosticCollection"
[IO.File]::WriteAllText("$testRoot\downloaded-core.ps1",$fixtureCore)
function New-Object {
param([string]$TypeName,[object[]]$ArgumentList)
if ($TypeName -eq 'Security.Principal.WindowsPrincipal') {
$principal=[pscustomobject]@{}
$principal | Add-Member ScriptMethod IsInRole { $true }
return $principal
}
if ($TypeName -eq 'Net.WebClient') {
$client=[pscustomobject]@{}
$client | Add-Member ScriptMethod DownloadString {param($Url) if ($Url -notlike '*/Get-OfficeDeploymentDiagnostics.ps1') {throw "Unexpected URL $Url"}; [IO.File]::ReadAllText("$testRoot\downloaded-core.ps1")}
return $client
}
Microsoft.PowerShell.Utility\New-Object @PSBoundParameters
}
function Get-OfficeDiagnosticRegistry { [pscustomobject]@{Name='ProductReleaseIds';Value='FixtureOffice'} }
function Get-CimInstance {
param($ClassName,$Filter,$ErrorAction)
switch ($ClassName) {
Win32_OperatingSystem { [pscustomobject]@{Caption='Fixture';LastBootUpTime=[datetime]'2026-10-30T08:00:00'} }
Win32_UserProfile { [pscustomobject]@{SID='S-1-fixture';LocalPath="$testRoot\other-user";Loaded=$false;Special=$false} }
Win32_Process { [pscustomobject]@{Name='powershell.exe';ProcessId=456;SessionId=2;CommandLine='powershell.exe -File C:\Temp\GetHelpElevated\fixture\Run.ps1'} }
Win32_Service { [pscustomobject]@{Name='ClickToRunSvc';State='Running'} }
default { throw "Unexpected CIM query $ClassName" }
}
}
function Invoke-CimMethod { [pscustomobject]@{Domain='Fixture';User='OtherUser';ReturnValue=0} }
function Get-ScheduledTask { @() }
foreach ($name in @('TEMP','LOCALAPPDATA','ProgramData','windir','COMPUTERNAME')) { $savedEnvironment[$name]=[Environment]::GetEnvironmentVariable($name,'Process') }
$env:TEMP="$testRoot\temp"; $env:LOCALAPPDATA="$testRoot\current-user"; $env:ProgramData="$testRoot\programdata"; $env:windir="$testRoot\Windows"; $env:COMPUTERNAME='FIXTURE'
foreach ($directory in @($env:TEMP,"$testRoot\other-user\AppData\Local\DAFs","$env:windir\Temp","$env:windir\SystemTemp\EmberkomOfficeDeployment\run\ODT")) { $null=New-Item -ItemType Directory -Path $directory -Force }
[IO.File]::WriteAllText("$testRoot\other-user\AppData\Local\DAFs\cse.amplify.diagaction.gethelp.officeuninstallalda_fixture.log",'Report from another user')
[IO.File]::WriteAllText("$env:windir\Temp\FIXTURE-20261030-0900.log",'Native install fixture')
[IO.File]::WriteAllText("$env:windir\SystemTemp\EmberkomOfficeDeployment\run\install.xml",'<Configuration />')
[IO.File]::WriteAllText("$env:windir\SystemTemp\EmberkomOfficeDeployment\run\ODT\setup.exe",'Excluded executable fixture')
$result=@(Run-Script -LivePSScript Get-OfficeDeploymentDiagnostics)
$bundle=@(Get-ChildItem -LiteralPath "$env:ProgramData\Emberkom\Logs\OfficeDiagnostics" -Filter '*.zip')
Assert-DiagnosticTest ($bundle.Count -eq 1 -and ($result -join "`n") -match 'Office diagnostic ZIP') 'The real RMM loader must execute the diagnostic core and return its ZIP path.'
$zip=[IO.Compression.ZipFile]::OpenRead($bundle[0].FullName)
try {
$manifest=Read-ZipText $zip 'manifest.json' | ConvertFrom-Json
$report=Read-ZipText $zip 'endpoint.json' | ConvertFrom-Json
Assert-DiagnosticTest (@($manifest | Where-Object {$_.Source -like '*other-user*DAFs*'}).Count -eq 1) 'DAF reports from profiles other than the caller must be captured.'
Assert-DiagnosticTest (@($manifest | Where-Object {$_.Source -like '*FIXTURE-20261030-0900.log'}).Count -eq 1) 'Native logs must be captured.'
Assert-DiagnosticTest (@($manifest | Where-Object {$_.Source -like '*install.xml'}).Count -eq 1 -and !@($manifest | Where-Object {$_.Source -like '*.exe'}).Count) 'Archive configurations but never installation media.'
Assert-DiagnosticTest ($report.Workers[0].Owner -eq 'Fixture\OtherUser' -and $report.Workers[0].SessionId -eq 2) 'Worker ownership and session must be recorded.'
Assert-DiagnosticTest ($report.OfficeRegistry[0].Value -eq 'FixtureOffice') 'Current Office state must be recorded separately from historical logs.'
} finally { $zip.Dispose() }
# Core failures must signal failure to RMM instead of claiming a ZIP was created.
$entry=$coreAst.EndBlock.Statements[-1].Extent.Text
[IO.File]::WriteAllText("$testRoot\failure.ps1", "function Invoke-OfficeDiagnosticCollection { throw 'Fixture collection failure' }`r`n$entry")
$ErrorActionPreference='Continue'
try { & $nativePowerShell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$testRoot\failure.ps1" *> "$testRoot\failure-output.log" }
finally { $ErrorActionPreference='Stop' }
Assert-DiagnosticTest ($LASTEXITCODE -eq 1) 'A failed diagnostic collection must exit 1.'
Write-Output "PASS: $script:assertions diagnostic assertions. Queries/downloads mocked; no Office changes."
} finally {
foreach ($name in $savedEnvironment.Keys) { [Environment]::SetEnvironmentVariable($name,$savedEnvironment[$name],'Process') }
$resolved=[IO.Path]::GetFullPath($testRoot)
if (!$resolved.StartsWith($originalTemp,[StringComparison]::OrdinalIgnoreCase) -or (Split-Path -Leaf $resolved) -notlike 'OfficeDiagnosticsTests-*') { throw 'Unsafe test cleanup path.' }
Remove-Item -LiteralPath $resolved -Recurse -Force -ErrorAction Stop
}
+524 -117
View File
@@ -350,7 +350,7 @@ try {
if ([IO.Path]::GetFileName($Path) -eq 'odt-download-page.html') { 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.' 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') [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.' Assert-OfficeTest ($Uri -eq (Get-OfficeDeploymentDefinitions).OfficeReleaseHistory) 'Windows 10 release lookup must use Microsoft history.'
[IO.File]::WriteAllText($Path, $script:mediaHistory) [IO.File]::WriteAllText($Path, $script:mediaHistory)
} elseif ([IO.Path]::GetFileName($Path) -eq 'Office-UserCleanup.ps1') { } elseif ([IO.Path]::GetFileName($Path) -eq 'Office-UserCleanup.ps1') {
@@ -389,7 +389,7 @@ try {
Assert-OfficeTest (($script:mediaProcesses -join ',') -eq 'odt.exe,setup.exe,setup.exe') 'Staging must only extract ODT and download Office, with no removal or installation.' Assert-OfficeTest (($script:mediaProcesses -join ',') -eq 'odt.exe,setup.exe,setup.exe') 'Staging must only extract ODT and download Office, with no removal or installation.'
$removal = [xml](Get-Content -LiteralPath $media.RemovalConfig -Raw) $removal = [xml](Get-Content -LiteralPath $media.RemovalConfig -Raw)
Assert-OfficeTest ($removal.Configuration.Remove.All -eq 'TRUE' -and $removal.Configuration.Display.Level -eq 'None') 'Staging must save the silent removal configuration.' Assert-OfficeTest ($removal.Configuration.Remove.All -eq 'TRUE' -and $removal.Configuration.Display.Level -eq 'None') 'Staging must save the silent removal configuration.'
Assert-OfficeTest (!$media.Scrubber -and !($script:mediaSignatures -match 'GetHelp|SaRA')) 'Unattended deployments must not stage an interactive scrubber.' Assert-OfficeTest (!$media.Scrubber -and !($script:mediaSignatures -match 'GetHelp|SaRA')) 'Ordinary media staging must not download the conditional scrubber.'
foreach ($mode in @('win10', 'incompatible-download', 'history-unavailable')) { foreach ($mode in @('win10', 'incompatible-download', 'history-unavailable')) {
$mediaWorkspace = Join-Path $testRoot $mode; $null = [IO.Directory]::CreateDirectory($mediaWorkspace) $mediaWorkspace = Join-Path $testRoot $mode; $null = [IO.Directory]::CreateDirectory($mediaWorkspace)
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Standard'; OfficeArchitecture='64'} $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Standard'; OfficeArchitecture='64'}
@@ -545,14 +545,18 @@ try {
& { & {
function Get-OfficeSuiteInventory { function Get-OfficeSuiteInventory {
$script:removalChecks++ $script:removalChecks++
if ($script:removalMode -eq 'empty') { return } if ($script:removalMode -in @('empty','orphan')) { return }
[pscustomobject]@{DisplayName='Microsoft Office Professional Plus 2016'; WindowsInstaller=1} [pscustomobject]@{DisplayName='Microsoft Office Professional Plus 2016'; WindowsInstaller=1}
if ($script:removalMode -eq 'msi-only') { return } if ($script:removalMode -eq 'msi-only') { return }
if ($script:removalStarted -and $script:removalMode -eq 'read-error') { throw 'Office inventory is unreadable' } if ($script:removalStarted -and $script:removalMode -eq 'read-error') { throw 'Office inventory is unreadable' }
if (!$script:removalStarted -or $script:removalMode -eq 'remaining' -or ($script:removalMode -eq 'delayed' -and $script:removalChecks -le 3)) { if (!$script:removalStarted -or $script:removalMode -in @('remaining','corrupt') -or ($script:removalMode -eq 'delayed' -and $script:removalChecks -le 3)) {
[pscustomobject]@{DisplayName='Microsoft Office Home and Business 2021 - en-us'} [pscustomobject]@{DisplayName='Microsoft Office Home and Business 2021 - en-us'}
} }
} }
function Get-OfficeClickToRunState { [pscustomobject]@{Present=($script:removalMode -eq 'orphan');SourceReferences=@();WorkingConfiguration=@($(if ($script:removalMode -eq 'stale') {'old-guid'}))} }
function Get-OfficeRemovalCorruptionEvidence { if ($script:removalMode -in @('corrupt','corrupt-gone')) { [pscustomobject]@{Path='fixture.log';Detail='REMOVEINSTALLATION InvalidDirectory'} } }
function Get-CimInstance { @() }
function Invoke-OfficeScrubRecovery { param($Media,$Workspace,$Reason) $script:scrubCalls++; Assert-OfficeTest (![string]::IsNullOrWhiteSpace($Reason)) 'Recovery must record its reason.'; return 3010 }
function Invoke-OfficeProcess { function Invoke-OfficeProcess {
param($FilePath,$Arguments,$LogPrefix) param($FilePath,$Arguments,$LogPrefix)
$script:removalCalls++; $script:removalStarted=$true $script:removalCalls++; $script:removalStarted=$true
@@ -563,25 +567,26 @@ try {
$removalPath = Join-Path $testRoot 'remove [literal].xml' $removalPath = Join-Path $testRoot 'remove [literal].xml'
(New-OfficeRemovalConfiguration ([pscustomobject]@{OfficeAppShutdown='Force'})).Save($removalPath) (New-OfficeRemovalConfiguration ([pscustomobject]@{OfficeAppShutdown='Force'})).Save($removalPath)
$media = [pscustomobject]@{Setup='inert-setup.exe'; RemovalConfig=$removalPath} $media = [pscustomobject]@{Setup='inert-setup.exe'; RemovalConfig=$removalPath}
foreach ($script:removalMode in @('empty','msi-only','mixed','delayed','remaining','read-error','fatal','reboot')) { foreach ($script:removalMode in @('empty','orphan','msi-only','mixed','delayed','remaining','stale','corrupt','corrupt-gone','unknown-17004','read-error','fatal','reboot')) {
$script:removalChecks=0; $script:removalCalls=0; $script:removalStarted=$false $script:removalChecks=0; $script:removalCalls=0; $script:removalStarted=$false; $script:scrubCalls=0
$script:removalCode = switch ($script:removalMode) { 'fatal' {1603}; 'reboot' {3010}; default {0} } $script:removalCode = switch ($script:removalMode) { 'fatal' {1603}; 'reboot' {3010}; 'corrupt' {17004}; 'corrupt-gone' {17004}; 'unknown-17004' {17004}; default {0} }
if ($script:removalMode -eq 'remaining') { if ($script:removalMode -eq 'remaining') {
Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'Office remains.*Office Home and Business 2021.*manual scrub' Assert-OfficeTest ((Remove-OfficeSuite $media $testRoot) -eq 3010) 'Verified leftovers after ODT success must select scrub recovery.'
Assert-OfficeTest ($script:removalChecks -eq ((Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts + 2)) 'Remaining Click-to-Run products must be checked for the bounded registration interval.' Assert-OfficeTest ($script:removalChecks -eq ((Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts + 2)) 'Remaining Click-to-Run products must be checked for the bounded registration interval.'
} elseif ($script:removalMode -eq 'read-error') { } elseif ($script:removalMode -eq 'read-error') {
Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'Office inventory is unreadable' Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'Office inventory is unreadable'
} elseif ($script:removalMode -eq 'fatal') { } elseif ($script:removalMode -in @('fatal','unknown-17004')) {
Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'ODT Office removal failed \(exit 1603\).*No interactive scrubber was launched.*manual scrub' Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'ODT Office removal failed.*automatic scrub was not selected'
} else { } else {
$result = @(Remove-OfficeSuite $media $testRoot) $result = @(Remove-OfficeSuite $media $testRoot)
$expected = if ($script:removalMode -eq 'reboot') {3010} else {0} $expected = if ($script:removalMode -in @('reboot','corrupt','corrupt-gone')) {3010} else {0}
Assert-OfficeTest ($result.Count -eq 1 -and $result[0] -eq $expected) 'Removal must return just its exit code; MSI products are deferred to installation.' Assert-OfficeTest ($result.Count -eq 1 -and $result[0] -eq $expected) 'Removal must return just its exit code; MSI products are deferred to installation.'
if ($script:removalMode -eq 'delayed') { Assert-OfficeTest ($script:removalChecks -eq 4) 'Removal must tolerate registry propagation delays.' } if ($script:removalMode -eq 'delayed') { Assert-OfficeTest ($script:removalChecks -eq 4) 'Removal must tolerate registry propagation delays.' }
if ($script:removalMode -eq 'reboot') { Assert-OfficeTest ($script:removalChecks -eq 1) 'A required restart must be surfaced before demanding registration cleanup.' } if ($script:removalMode -eq 'reboot') { Assert-OfficeTest ($script:removalChecks -eq 1) 'A required restart must be surfaced before demanding registration cleanup.' }
} }
$expectedCalls = if ($script:removalMode -in @('empty','msi-only')) {0} else {1} $expectedCalls = if ($script:removalMode -in @('empty','orphan','msi-only')) {0} else {1}
Assert-OfficeTest ($script:removalCalls -eq $expectedCalls) 'Do not remove absent Click-to-Run Office, rerun failed removal, or launch a fallback scrubber.' Assert-OfficeTest ($script:removalCalls -eq $expectedCalls) 'Run removal only for registered Click-to-Run products, never merely an orphaned service/registry key.'
Assert-OfficeTest ($script:scrubCalls -eq $(if ($script:removalMode -in @('corrupt','remaining')) {1} else {0})) 'Only failed removal with products remaining may trigger a single scrub; metadata or no products must not.'
} }
} }
& { & {
@@ -833,86 +838,443 @@ 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.' 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. # Classify only current, removal-specific corruption; stale errors in a live
# service log and generic 17004 wrappers must not authorize a destructive scrub.
& { & {
$cacheRoot = Join-Path $testRoot 'cache-tests'; $null = [IO.Directory]::CreateDirectory($cacheRoot) $path=Join-Path $testRoot 'Office-corruption.log'
$source = Join-Path $cacheRoot ('a' * 32); $null = [IO.Directory]::CreateDirectory($source) function Get-OfficeSetupLogFiles { Get-Item -LiteralPath $path }
# LiteralPath matters: the staged fixture intentionally contains brackets. $since=[DateTime]::UtcNow.AddSeconds(-2)
foreach ($file in Get-ChildItem -LiteralPath (Join-Path $testRoot 'media [literal]')) { Copy-Item -LiteralPath $file.FullName -Destination $source -Recurse } $stamp=[DateTime]::Now.ToString('M/d/yyyy H:mm:ss.fff', [Globalization.CultureInfo]::InvariantCulture)
$target = Join-Path $cacheRoot ('b' * 32); $null = [IO.Directory]::CreateDirectory($target) $detail='OFFICECL Click-To-Run Non Task Error {"ErrorCode":30034,"ErrorType":"InvalidDirectory","ErrorMessage":"GetFiles: search path root\\integration does not exist","Task":"REMOVEINSTALLATION:{A1D863B9-4F69-45AF-BD5C-D349E5C0C851}"}'
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeArchitecture='64'; COMPANY='New Company'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'} Set-Content -LiteralPath $path -Value "$stamp`t$detail"
$script:rejectCacheSignature = $false; $script:helperDownloads = 0 $evidence=Get-OfficeRemovalCorruptionEvidence $since
function Get-CimInstance { } Assert-OfficeTest ($evidence.Path -eq $path -and $evidence.Detail.Contains('root\\integration')) 'The observed InvalidDirectory removal error must trigger recovery evidence.'
function Assert-OfficeDiskSpace { throw 'Cache reuse must not request fresh-download disk reserve; the main workflow checks installation space afterward.' } foreach ($line in @(
function Assert-OfficeMicrosoftSignature { param($Path) if ($script:rejectCacheSignature) { throw 'Untrusted cache signature' }; Assert-OfficeTest (Test-Path -LiteralPath $Path) 'Cache signature target was missing.' } ('10/22/2026 13:57:00.000' + "`t" + $detail),
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) } ("$stamp`t" + $detail.Replace('REMOVEINSTALLATION', 'INSTALL')),
function Invoke-OfficeProcess { throw 'A cached deployment must not redownload Office.' } ("$stamp`t" + $detail.Replace('InvalidDirectory', 'AccessDenied')),
$manifestPath = Join-Path $source 'media-cache.json' ("$stamp`tSETUP unknown error [ExitCode=17004]"),
$originalManifest = Get-Content -LiteralPath $manifestPath -Raw ('No timestamp ' + $detail),
Assert-OfficeTest (!($originalManifest | ConvertFrom-Json).Files[0].PSObject.Properties['Hash']) 'Cache manifests must not store file checksums.' ([DateTime]::Now.AddHours(1).ToString('M/d/yyyy H:mm:ss.fff', [Globalization.CultureInfo]::InvariantCulture) + "`t" + $detail)
$different = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5'; OfficeArchitecture='64'} )) {
Assert-OfficeTest (!(Restore-OfficeMediaCache $different $target)) 'Teams selection mismatch reused the wrong cache.' Set-Content -LiteralPath $path -Value $line
$different = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeArchitecture='64'; UpdateChannel='MonthlyEnterprise'} Assert-OfficeTest ($null -eq (Get-OfficeRemovalCorruptionEvidence $since)) 'Old, unrelated, unparseable and future evidence must not select recovery.'
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'} function Get-Content { throw 'Log locked' }
$different.TargetOfficeVersion='16.0.20326.20158' Assert-OfficeTest ($null -eq (Get-OfficeRemovalCorruptionEvidence $since)) 'Unreadable evidence must not select recovery.'
Assert-OfficeTest (!(Restore-OfficeMediaCache $different $target)) 'A Windows 10 target reused incompatible unpinned media.' }
$manifest = $originalManifest | ConvertFrom-Json; $manifest.Key = Get-OfficeMediaCacheKey $different # Download/extract only on demand, validate the Microsoft executable, and never
$manifest | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $manifestPath # rely on Tools.ps1's shadowed Expand-Archive or a previously extracted package.
Assert-OfficeTest (!(Restore-OfficeMediaCache $different $target)) 'A matching cache key hid an incompatible Windows 10 payload version.' & {
$manifest = $originalManifest | ConvertFrom-Json; $manifest.Schema = 1 Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem
$manifest | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $manifestPath $script:scrubPackageMode='single'; $script:scrubSignatures=@(); $script:scrubDownloads=0
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
function Save-OfficeDownload { function Save-OfficeDownload {
param($Uri,$Path) param($Uri,$Path)
switch ([IO.Path]::GetFileName($Path)) { Assert-OfficeTest ($Uri -eq (Get-OfficeDeploymentDefinitions).GetHelpUrl) 'Recovery must use the current Microsoft download link.'
'office-release-history.html' { [IO.File]::WriteAllText($Path, $releaseHistory) } $script:scrubDownloads++
'Office-UserCleanup.ps1' { [IO.File]::WriteAllText($Path, '# ' + (Get-OfficeDeploymentDefinitions).HelperVersion) } $zip=[IO.Compression.ZipFile]::Open($Path, [IO.Compression.ZipArchiveMode]::Create)
default { throw 'Unexpected installer download on Windows 10 cache hit' } try {
$entries = switch ($script:scrubPackageMode) {
'traversal' { @('../escaped.exe') }
'missing' { @('readme.txt') }
'duplicate' { @('one/GetHelpCmd.exe','two/GetHelpCmd.exe') }
default { @('GetHelpCmd.exe','support.dll') }
}
foreach ($name in $entries) { $entry=$zip.CreateEntry($name); $writer=[IO.StreamWriter]::new($entry.Open()); try { $writer.Write('Inert archive fixture, never executed.') } finally { $writer.Dispose() } }
} finally { $zip.Dispose() }
}
function Assert-OfficeMicrosoftSignature { param($Path) $script:scrubSignatures += $Path; if ($script:scrubPackageMode -eq 'unsigned') { throw 'Invalid Microsoft signature' } }
function Expand-Archive { throw 'Must use the literal-path Archive module, not the Tools override.' }
foreach ($script:scrubPackageMode in @('single','missing','duplicate','traversal','unsigned')) {
$workspace=Join-Path $testRoot ('scrub package [' + $script:scrubPackageMode + ']'); $null=[IO.Directory]::CreateDirectory($workspace)
if ($script:scrubPackageMode -eq 'single') {
$exe=Initialize-OfficeScrubMedia $workspace
Assert-OfficeTest ($exe -eq (Join-Path $workspace 'GetHelp\GetHelpCmd.exe') -and $exe -in $script:scrubSignatures) 'Freshly extracted Get Help must pass signature verification.'
$before=$script:scrubDownloads
Assert-OfficeThrows { Initialize-OfficeScrubMedia $workspace } 'refusing to reuse'
Assert-OfficeTest ($script:scrubDownloads -eq $before) 'A second recovery must not download or reuse its package.'
} elseif ($script:scrubPackageMode -eq 'traversal') {
Assert-OfficeThrows { Initialize-OfficeScrubMedia $workspace } 'outside the Office deployment root'
Assert-OfficeTest (!(Test-Path -LiteralPath (Join-Path $workspace 'escaped.exe'))) 'ZIP extraction must not escape its folder.'
} elseif ($script:scrubPackageMode -eq 'unsigned') { Assert-OfficeThrows { Initialize-OfficeScrubMedia $workspace } 'Invalid Microsoft signature' }
else { Assert-OfficeThrows { Initialize-OfficeScrubMedia $workspace } 'exactly one GetHelpCmd.exe' }
}
}
# Scrub console details must reach the management log even when no recognizable
# scenario code is emitted; excerpts are bounded without altering parser input.
& {
$prefix=Join-Path $testRoot 'scrub-output'
$stdout="Tool startup message without scenario code`n" + (('x' * 2100) + "`n") + ((1..25 | ForEach-Object { "progress $_" }) -join "`n")
$stderr='A diagnostic from stderr'
[IO.File]::WriteAllText("$prefix.stdout.log", $stdout)
[IO.File]::WriteAllText("$prefix.stderr.log", $stderr)
$output=@(Read-OfficeScrubOutput $prefix)
Assert-OfficeTest ($output.Count -eq 1 -and $output[0] -ceq ($stdout + "`n" + $stderr)) 'Diagnostic excerpts must not change the complete scrub output used for result parsing.'
$log=Get-Content -LiteralPath $Global:LogFile -Raw
Assert-OfficeTest ($log.Contains('Get Help stderr detail: A diagnostic from stderr') -and $log.Contains('Get Help stdout: ')) 'Both stream sizes and captured text must reach the main management log.'
Assert-OfficeTest ($log.Contains('Get Help stdout detail: Tool startup message without scenario code') -and $log.Contains('Get Help stdout detail: progress 25') -and !$log.Contains('Get Help stdout detail: progress 14' + [Environment]::NewLine) -and $log.Contains('[middle output omitted; see full stream log]')) 'Bounded scrub excerpts must retain initial failures and final results.'
[IO.File]::WriteAllText("$prefix.stdout.log", 'x' * 2100)
[IO.File]::WriteAllText("$prefix.stderr.log", '')
$null=Read-OfficeScrubOutput $prefix
$log=Get-Content -LiteralPath $Global:LogFile -Raw
Assert-OfficeTest ($log.Contains('[truncated; see full stream log]') -and $log.Contains('Get Help stderr: no text captured.')) 'Oversized lines and empty streams must be explicit in the management log.'
}
# Restore runtime syntax detection instead of trusting stale published switches.
& {
$usage='GetHelpCmd.exe -S OfficeScrubScenario -AcceptEula'
Assert-OfficeTest ((Get-OfficeScrubArguments 0 $usage) -eq '-S OfficeScrubScenario -AcceptEula') 'Current tool usage must omit unsupported OfficeVersion.'
Assert-OfficeTest ((Get-OfficeScrubArguments 0 ($usage + "`n -OfficeVersion <version>")) -eq '-S OfficeScrubScenario -AcceptEula -OfficeVersion All') 'A tool advertising OfficeVersion must request all versions.'
Assert-OfficeThrows { Get-OfficeScrubArguments 1 $usage } 'Could not validate'
Assert-OfficeThrows { Get-OfficeScrubArguments 0 ($usage + "`nError: Invalid command line arguments") } 'Could not validate'
Assert-OfficeThrows { Get-OfficeScrubArguments 0 'No OfficeScrubScenario example' } 'Could not validate'
}
& {
function Get-CimInstance {
param($ClassName,$Filter)
Assert-OfficeTest ($ClassName -eq 'Win32_Process' -and $Filter.Contains("Name='powershell.exe'")) 'Worker monitoring must inspect detached script hosts.'
[pscustomobject]@{Name='powershell.exe';ProcessId=$PID;CommandLine='self'}
[pscustomobject]@{Name='powershell.exe';ProcessId=9701;CommandLine='powershell.exe -File C:\Temp\GetHelpElevated\abc\Run.ps1'}
[pscustomobject]@{Name='msiexec.exe';ProcessId=9702;CommandLine='msiexec.exe /V'}
[pscustomobject]@{Name='OfficeClickToRun.exe';ProcessId=9703;CommandLine='OfficeClickToRun.exe /service'}
[pscustomobject]@{Name='OfficeClickToRun.exe';ProcessId=9704;CommandLine='OfficeClickToRun.exe /user'}
[pscustomobject]@{Name='msiexec.exe';ProcessId=9705;CommandLine='msiexec.exe /x {fixture}'}
}
$workers=@(Get-OfficeScrubWorkers)
Assert-OfficeTest ($workers.Count -eq 2 -and 9701 -in $workers.ProcessId -and 9705 -in $workers.ProcessId) 'Detached cleanup and active MSI workers matter; the caller and idle service hosts do not.'
}
# Verify actual process-handle retention using only an inert child, never a scrubber.
& {
$encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes('Start-Sleep -Milliseconds 1500; exit 7'))
$probe=Start-Process -FilePath (Join-Path $PSHOME 'powershell.exe') -ArgumentList "-NoProfile -NonInteractive -EncodedCommand $encoded" -WindowStyle Hidden -PassThru
$held=$null
try {
$identity=Get-CimInstance Win32_Process -Filter "ProcessId=$($probe.Id)" -ErrorAction Stop
$held=Open-OfficeScrubWorkerHandle $identity
Assert-OfficeTest ($held.WaitForExit(10000) -and $held.ExitCode -eq 7) 'A held handle must preserve a failed worker exit after its PID disappears.'
Assert-OfficeThrows { Open-OfficeScrubWorkerHandle ([pscustomobject]@{ProcessId=$PID;CreationDate=[datetime]'2000-01-01'}) } 'Process identity changed'
} finally { if ($held) { $held.Dispose() }; $probe.Dispose() }
}
# Captured endpoint report: the launcher returned success, but the worker had
# already reported no supported products and was waiting in Console.ReadKey.
& {
$reports=Join-Path $testRoot 'DAFs'; $null=New-Item -ItemType Directory -Path $reports
$reportPath=Join-Path $reports 'cse.amplify.diagaction.gethelp.officeuninstallalda_fixture.log'
Copy-Item -LiteralPath (Join-Path $repo 'tests\fixtures\office\scrub-no-products.log') -Destination $reportPath
# Copy-Item preserves LastWriteTime; set both times to model a newly written report.
[IO.File]::SetCreationTimeUtc($reportPath,[datetime]::UtcNow)
[IO.File]::SetLastWriteTimeUtc($reportPath,[datetime]::UtcNow)
$worker=[pscustomobject]@{CreationDate=[datetime]::UtcNow.AddMinutes(-1)}
$result=@(Read-OfficeScrubWorkerReport $worker @($reports))
Assert-OfficeTest ($result.Count -eq 1 -and $result[0].Result -eq 'Failed' -and $result[0].Detail -eq 'There are no supported Office products installed.') 'Parse the actual failed scrub report, not the launcher success acknowledgment.'
$worker.CreationDate=[datetime]::UtcNow.AddMinutes(1)
Assert-OfficeTest (@(Read-OfficeScrubWorkerReport $worker @($reports)).Count -eq 0) 'An old report must never be attributed to a new worker.'
$worker.CreationDate=[datetime]::UtcNow.AddMinutes(-1)
Set-Content -LiteralPath $reportPath -Value 'Report: {"ExecutionResult":'
Assert-OfficeTest (@(Read-OfficeScrubWorkerReport $worker @($reports)).Count -eq 0) 'A report being written must not be interpreted as completed.'
Set-Content -LiteralPath $reportPath -Value 'Report: {"ExecutionResult":"Failed","TroubleshooterName":"OtherScenario"}'
Assert-OfficeTest (@(Read-OfficeScrubWorkerReport $worker @($reports)).Count -eq 0) 'Reports from another scenario must be ignored.'
function Invoke-CimMethod { [pscustomobject]@{ReturnValue=0;Sid='S-1-5-18'} }
$roots=@(Get-OfficeScrubReportRoots ([pscustomobject]@{ProcessId=9701}))
Assert-OfficeTest ($roots.Count -eq 2 -and $roots[0] -like '*systemprofile*\DAFs') 'SYSTEM reports must be sought in both system-profile locations.'
function Invoke-CimMethod { [pscustomobject]@{ReturnValue=0;Sid='S-1-fixture'} }
function Get-ItemPropertyValue { 'C:\Users\ScrubOwner' }
Assert-OfficeTest ((Get-OfficeScrubReportRoots ([pscustomobject]@{ProcessId=9701})) -eq 'C:\Users\ScrubOwner\AppData\Local\DAFs') 'Other worker reports must use that worker owner profile, not the RMM caller profile.'
}
# A background launch is pending. Workers must finish successfully and removal
# state must stay clean for the entire quiet interval; closing early is not success.
& {
$existing=[pscustomobject]@{Name='powershell.exe';ProcessId=8001;CreationDate=[datetime]'2026-10-29T12:00:00';CommandLine='powershell.exe -NoProfile'}
$fixtureScrubWorker=[pscustomobject]@{Name='powershell.exe';ProcessId=9701;CreationDate=[datetime]'2026-10-29T16:00:00';CommandLine='powershell.exe -File C:\Temp\GetHelpElevated\abc\Run.ps1'}
function Get-OfficeScrubReportRoots { @() }
function Read-OfficeScrubWorkerReport {
if ($script:waitMode -eq 'report-failed') { [pscustomobject]@{Result='Failed';Detail='There are no supported Office products installed.';Path='fixture-report.log'} }
}
function Get-OfficeScrubWorkers {
$script:waitPoll++
if ($script:waitMode -eq 'process-error') { throw 'Process inventory unreadable' }
$existing
if ($script:waitMode -ne 'no-worker' -and ($script:waitPoll -le 2 -or $script:waitMode -eq 'keypress')) { $fixtureScrubWorker }
if ($script:waitMode -eq 'quiet-reset' -and $script:waitPoll -eq 5) { [pscustomobject]@{Name='setup.exe';ProcessId=9702;CreationDate=$fixtureScrubWorker.CreationDate;CommandLine='setup.exe'} }
}
function Open-OfficeScrubWorkerHandle {
param($Worker)
$script:openCalls++
if ($script:waitMode -eq 'lost-handle') { throw 'Could not monitor scrub worker PID 9701' }
$handle=[pscustomobject]@{ExitCode=$(if ($script:waitMode -eq 'closed') {-1073741510} elseif ($script:waitMode -eq 'failed') {1} elseif ($script:waitMode -eq 'restart') {3010} else {0})}
$handle | Add-Member ScriptProperty HasExited { $script:waitPoll -gt 2 -and $script:waitMode -ne 'keypress' }
$handle | Add-Member ScriptMethod Dispose { $script:disposed++ }
$handle
}
function Get-OfficeSuiteInventory {
if ($script:waitMode -eq 'inventory-error') { throw 'Office inventory unreadable' }
if ($script:waitMode -eq 'remaining' -or ($script:waitMode -eq 'delayed' -and $script:waitPoll -le 4)) { [pscustomobject]@{DisplayName='Old Office'} }
}
function Get-OfficeClickToRunState {
$script:waitStateReads++
if ($script:waitMode -eq 'state-error') { throw 'Servicing state unreadable' }
[pscustomobject]@{SourceReferences=@($(if ($script:waitMode -eq 'stale') {'old-download'}));WorkingConfiguration=@()}
}
foreach ($script:waitMode in @('success','restart','delayed','quiet-reset','closed','failed','remaining','stale','no-worker','keypress','process-error','inventory-error','report-failed','lost-handle')) {
$script:waitPoll=0; $script:disposed=0; $script:openCalls=0; $script:testSleeps=@(); $script:waitStateReads=0
if ($script:waitMode -in @('success','restart','delayed','quiet-reset','stale')) {
$result=@(Wait-OfficeScrubRemoval @($existing))
$expectedPolls=switch ($script:waitMode) { 'delayed' {11}; 'quiet-reset' {12}; default {9} }
Assert-OfficeTest ($result.Count -eq 0 -and $script:waitPoll -eq $expectedPolls) 'Background verification must wait for workers, delayed removal, and a continuous 60-second quiet interval without leaking output.'
} else {
$pattern=switch ($script:waitMode) { 'closed' {'exited unsuccessfully.*-1073741510'}; 'failed' {'exited unsuccessfully.*exit 1'}; 'process-error' {'Process inventory unreadable'}; 'inventory-error' {'Office inventory unreadable'}; 'state-error' {'Servicing state unreadable'}; 'lost-handle' {'Could not monitor scrub worker'}; default {'background removal did not finish verification'} }
if ($script:waitMode -eq 'keypress') { $pattern = 'Office registrations remaining: 0.*will not resume automatically.*success OR failure' }
if ($script:waitMode -eq 'report-failed') { $pattern = 'worker reported failure: There are no supported Office products installed.*fixture-report.log' }
Assert-OfficeThrows { Wait-OfficeScrubRemoval @($existing) } $pattern
if ($script:waitMode -eq 'keypress') { Assert-OfficeTest ($script:waitStateReads -eq 0) 'A live cleanup worker defers the servicing-state check; it does not prove stale state.' }
if ($script:waitMode -eq 'report-failed') { Assert-OfficeTest ($script:waitPoll -eq 1 -and !$script:testSleeps.Count) 'A terminal failed report must stop immediately, without a 30-minute keypress wait.' }
if ($script:waitMode -in @('remaining','stale','no-worker','keypress')) { Assert-OfficeTest (($script:testSleeps | Measure-Object -Sum).Sum -eq 1800) 'Unfinished background removal must stop after the restored 30-minute wait.' }
}
Assert-OfficeTest ($script:disposed -eq $(if ($script:waitMode -in @('process-error','no-worker','lost-handle')) {0} else {1})) 'Every acquired worker handle must be released on success and failure.'
Assert-OfficeTest ($script:openCalls -le 1) 'Polling must retain the same worker handle rather than reopening a possibly reused PID.'
Assert-OfficeTest ($script:waitStateReads -eq 0) 'Servicing metadata is not a scrub completion criterion.'
}
}
# A scrub requires both a successful scenario/process result and independently
# verified removal. Every attempt is bounded to one and cleanup retains its logs.
& {
$script:scrubLaunches=0
function Initialize-OfficeScrubMedia {
param($Workspace)
Set-Content -LiteralPath (Join-Path $Workspace 'GetHelp.zip') -Value 'fixture'
if ($script:scrubMode -eq 'download') { throw 'Scrub download failed' }
Join-Path $Workspace 'GetHelpCmd.exe'
}
function Invoke-OfficeProcess {
param($FilePath,$Arguments,$LogPrefix)
if ($Arguments -eq '-?') {
$script:usageCalls++
Set-Content -LiteralPath "$LogPrefix.stdout.log" -Value $(if ($script:scrubMode -eq 'bad-help') {'Usage unavailable'} else {'GetHelpCmd.exe -S OfficeScrubScenario -AcceptEula'})
Set-Content -LiteralPath "$LogPrefix.stderr.log" -Value ''
return 0
}
$script:scrubLaunches++
Assert-OfficeTest ($Arguments -eq '-S OfficeScrubScenario -AcceptEula' -and (Split-Path -Leaf $LogPrefix) -eq 'office-scrub') 'Scrub must use the current tool-supported arguments, omitting the rejected OfficeVersion option.'
Set-Content -LiteralPath "$LogPrefix.stdout.log" -Value $script:scrubOutput
Set-Content -LiteralPath "$LogPrefix.stderr.log" -Value ''
$script:scrubExit
}
function Get-OfficeScrubWorkers { if ($script:scrubMode -eq 'preexisting-worker') { [pscustomobject]@{Name='powershell.exe';ProcessId=8000;CommandLine='powershell.exe -File C:\Temp\GetHelpElevated\old\Run.ps1'} } }
function Wait-OfficeScrubRemoval {
param($ExistingWorkers)
$script:backgroundWaits++
if ($script:scrubMode -eq 'background-no-worker') { throw 'Get Help background removal did not finish verification within the allowed time.' }
}
function Get-CimInstance {
if ($script:scrubMode -eq 'preexisting-worker') { Get-OfficeScrubWorkers }
if ($script:scrubMode -eq 'running') { [pscustomobject]@{Name='GetHelpCmd.exe'} }
if ($script:scrubMode -eq 'background') { [pscustomobject]@{Name='powershell.exe';ProcessId=7064;CommandLine='powershell.exe -File C:\Windows\SystemTemp\GetHelpElevated\d509ee113e5346fa82eded7e01f47f69\Run.ps1'} }
}
function Get-OfficeSuiteInventory {
if ($script:scrubMode -eq 'remaining') { [pscustomobject]@{DisplayName='Leftover MSI Office';WindowsInstaller=1} }
if ($script:scrubMode -eq 'inventory-error') { throw 'Registry unreadable' }
}
function Assert-OfficeRemovalComplete { if ($script:scrubMode -eq 'stale') { throw 'Removal verification failed' } }
foreach ($script:scrubMode in @('success','restart','download','bad-help','preexisting-worker','failure','not-found-66','not-found-68','empty','invalid-arguments','usage','background','background-no-worker','background-with-00','generic-success','text-error','background-bad-exit','background-error','contradictory','bad-exit','running','remaining','inventory-error','stale')) {
$workspace=Join-Path $testRoot ('scrub-result-' + $script:scrubMode); $null=[IO.Directory]::CreateDirectory($workspace)
$media=[pscustomobject]@{}; $script:scrubExit=0; $script:scrubOutput='00: Successfully completed this scenario.'; $script:backgroundWaits=0; $script:usageCalls=0
switch ($script:scrubMode) {
'restart' { $script:scrubExit=3010 }
'failure' { $script:scrubOutput='09: Failure to remove Office.' }
'not-found-66' { $script:scrubOutput='66: We could not find the specified Office version.'; $script:scrubExit=66 }
'not-found-68' { $script:scrubOutput='68: We could not find any Office version.' }
'empty' { $script:scrubOutput='' }
'invalid-arguments' { $script:scrubOutput="Starting Microsoft GetHelp Command Line Tool`nError: Invalid command line arguments`nUsage: GetHelpCmd.exe [options]`nExamples:`nGetHelpCmd.exe -S OfficeScrubScenario -AcceptEula" }
'usage' { $script:scrubOutput="Usage: GetHelpCmd.exe [options]`n00: Success" }
{ $_ -like 'background*' } { $script:scrubOutput="Starting Microsoft GetHelp Command Line Tool`nDiagnostic action completed.`nScenario completed successfully.`nExecutionResultDetails: Uninstall office is running in the background."; if ($_ -eq 'background-with-00') { $script:scrubOutput += "`n00: Success" } }
'generic-success' { $script:scrubOutput='Scenario completed successfully.' }
'text-error' { $script:scrubOutput="Error: Removal failed`nScenario completed successfully." }
'background-error' { $script:scrubOutput += "`nError: Removal failed" }
'background-bad-exit' { $script:scrubExit=1 }
'contradictory' { $script:scrubOutput="09: Failure`n00: Success" }
'bad-exit' { $script:scrubExit=1 }
}
if ($script:scrubMode -in @('success','restart','generic-success','background-with-00')) {
$result=@(Invoke-OfficeScrubRecovery $media $workspace 'fixture corruption')
Assert-OfficeTest ($result.Count -eq 1 -and $result[0] -eq 3010 -and $media.ScrubAttempted -and $media.ScrubReason -eq 'fixture corruption') 'Verified scrub must surface its use and restart requirement without leaking log messages.'
} else {
$pattern=switch ($script:scrubMode) { 'download' {'Scrub download failed'}; 'bad-help' {'Could not validate.*Scrub was not launched'}; 'preexisting-worker' {'Cannot launch scrub.*worker is running'}; 'invalid-arguments' {'rejected its command line.*process 0'}; 'usage' {'rejected its command line.*process 0'}; 'background-no-worker' {'background removal did not finish verification'}; 'background' {'processes are still running'}; 'running' {'processes are still running'}; 'remaining' {'Office remains.*Leftover MSI Office'}; 'inventory-error' {'Registry unreadable'}; 'stale' {'Removal verification failed'}; default {'failed or returned an unverified result'} }
Assert-OfficeThrows { Invoke-OfficeScrubRecovery $media $workspace 'fixture corruption' } $pattern
}
Assert-OfficeTest ($script:usageCalls -eq $(if ($script:scrubMode -eq 'download') {0} else {1})) 'Probe the fresh scrubber usage exactly once, only after recovery was selected.'
Assert-OfficeTest ($script:backgroundWaits -eq $(if ($script:scrubMode -in @('background','background-no-worker','background-with-00')) {1} else {0})) 'Only an accepted background launch may enter the completion wait.'
$before=$script:scrubLaunches
Assert-OfficeThrows { Invoke-OfficeScrubRecovery $media $workspace 'second attempt' } 'already attempted'
Assert-OfficeTest ($script:scrubLaunches -eq $before) 'Failure must not create a scrub loop.'
$warnings=Complete-OfficeDeploymentFiles $workspace
if ($script:scrubMode -in @('running','background','preexisting-worker')) { Assert-OfficeTest ($warnings.Count -gt 0 -and (Test-Path -LiteralPath (Join-Path $workspace 'GetHelp.zip'))) 'Surviving scrub workers must retain in-use media.' }
else {
Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath (Join-Path $workspace 'GetHelp.zip'))) 'Scrub download must be removed on success and failure.'
if ($script:scrubMode -notin @('download','bad-help')) { Assert-OfficeTest (Test-Path -LiteralPath (Join-Path $workspace 'office-scrub.stdout.log')) 'Scrub result logs must survive cleanup.' }
} }
} }
$media = Initialize-OfficeMedia $options $win10Target Assert-OfficeTest (Test-OfficeStagingInUse $testRoot @([pscustomobject]@{Name='cscript.exe';CommandLine='cscript.exe C:\Temp\OffScrubC2R.vbs ALL'})) 'Detached Office scrub scripts must block a new deployment and media cleanup.'
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 # Get Help's detached signed launcher lives outside the deployment workspace
# helpers have a separate durable folder and are never part of the media cache. # and can remain at Console.ReadKey after either success or failure.
& {
$worker=[pscustomobject]@{Name='powershell.exe';ProcessId=7064;CommandLine='"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File C:\Windows\SystemTemp\GetHelpElevated\d509ee113e5346fa82eded7e01f47f69\Run.ps1 C:\Windows\SystemTemp\GetHelpElevated\d509ee113e5346fa82eded7e01f47f69'}
$root=Join-Path $testRoot 'detached-gethelp'; $workspace=Join-Path $root ('a'*32)
$null=[IO.Directory]::CreateDirectory($workspace)
$payload=Join-Path $workspace 'GetHelp.zip'; Set-Content -LiteralPath $payload -Value 'fixture'
function Get-CimInstance { $worker }
function Get-OfficeDeploymentRoots { $root }
function Get-ScheduledTask { throw 'Worker guard must run before retiring tasks.' }
Assert-OfficeTest (Test-OfficeStagingInUse $workspace @($worker)) 'GetHelpElevated Run.ps1 must block cleanup despite not naming our workspace.'
Assert-OfficeTest (@(Get-OfficeBlockingProcesses $workspace @($worker)).Count -eq 1) 'A worker must be returned once for diagnostics.'
Assert-OfficeThrows { Clear-OfficePreviousDeploymentFiles } 'surviving installer.*powershell.exe \(PID 7064\)'
$warnings=Complete-OfficeDeploymentFiles $workspace
Assert-OfficeTest ($warnings.Count -gt 0 -and (Test-Path -LiteralPath $payload)) 'Detached Get Help workers must preserve media on failure as well as block fresh downloads.'
$quoted=[pscustomobject]@{Name='powershell.exe';CommandLine='powershell.exe -File "C:\Temp Folder\GETHELPELEVATED\abc\run.ps1" "C:\Temp Folder\GETHELPELEVATED\abc"'}
Assert-OfficeTest (Test-OfficeStagingInUse $workspace @($quoted)) 'Quoted Get Help worker paths must be recognized case-insensitively.'
$ordinary=@([pscustomobject]@{Name='powershell.exe';CommandLine='powershell.exe -File C:\Tools\Run.ps1'},[pscustomobject]@{Name='OfficeClickToRun.exe';CommandLine='OfficeClickToRun.exe /service'},[pscustomobject]@{Name='OfficeClickToRun.exe';CommandLine='OfficeClickToRun.exe /user'})
$ordinary += @([pscustomobject]@{Name='msiexec.exe';CommandLine='msiexec.exe /V'},[pscustomobject]@{Name='msiexec.exe';CommandLine='msiexec.exe /Embedding fixture'})
Assert-OfficeTest (!(Test-OfficeStagingInUse $workspace $ordinary)) 'Unrelated PowerShell and idle Click-to-Run/MSI hosts must not block completed cleanup.'
Assert-OfficeTest (Test-OfficeStagingInUse $workspace @([pscustomobject]@{Name='msiexec.exe';CommandLine='msiexec.exe /x {fixture} /quiet'})) 'Active MSI uninstall clients must still protect the workspace.'
}
# Deployment resolves release metadata and deletes it on success or failure.
& {
$script:historyPaths=@()
function Save-OfficeDownload {
param($Uri,$Path)
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 $testRoot
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 $testRoot
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 $testRoot } 'did not identify'
Assert-OfficeTest (!(Test-Path -LiteralPath $script:historyPaths[-1])) 'Failed preflight retained release metadata.'
}
# Assessment uses HEAD only, follows redirects, requires 200, and never saves data.
& {
$script:heads=@(); $script:headCode=200; $script:headFails=$false
function Invoke-WebRequest {
param([switch]$UseBasicParsing,$Method,$Uri,$MaximumRedirection,$TimeoutSec,$ErrorAction,[switch]$OutFile)
Assert-OfficeTest ($Method -eq 'Head' -and $MaximumRedirection -eq 10 -and !$OutFile) 'Assessment must use HEAD with redirect handling and no output file.'
$script:heads += $Uri
if ($script:headFails) { throw 'HEAD unsupported' }
[pscustomobject]@{StatusCode=$script:headCode}
}
function Save-OfficeDownload { throw 'Assessment must not download data.' }
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'}
$checks = @(Test-OfficeDownloadLinks $options)
Assert-OfficeTest ($checks.Count -eq 7 -and $checks.Count -eq $script:heads.Count) 'HEAD checks must cover ODT discovery, helper, recovery link, CDN, and selected companions.'
Assert-OfficeTest ((Get-OfficeDeploymentDefinitions).CompanionInstallers.Teams.Uri -notin $script:heads) 'No-Teams assessment must not probe the Teams download.'
$options.InstallTeams=$true; $options.OfficeFeatureRelease='2608'; $script:heads=@()
$checks = @(Test-OfficeDownloadLinks $options)
Assert-OfficeTest ($checks.Count -eq 9 -and (Get-OfficeDeploymentDefinitions).OfficeReleaseHistory -in $script:heads) 'Windows 10 assessment must check history availability without resolving the build.'
$script:headCode=204
Assert-OfficeThrows { Test-OfficeDownloadLinks $options } 'returned 204; expected 200'
$script:headFails=$true
Assert-OfficeThrows { Test-OfficeDownloadLinks $options } 'HEAD check failed.*HEAD unsupported'
$path = Join-Path $testRoot 'not-created\EmberkomOfficeDeployment'
$before = @(Get-ChildItem -LiteralPath $testRoot -Force).Count
$result = Assert-OfficeWritablePath $path
Assert-OfficeTest (!(Test-Path -LiteralPath $path) -and $result.TestedDirectory -eq $testRoot -and @(Get-ChildItem -LiteralPath $testRoot -Force).Count -eq $before) 'Write checks must remove probes and never create deployment directories.'
$file = Join-Path $testRoot 'not-a-directory'; Set-Content -LiteralPath $file -Value 'fixture'
Assert-OfficeThrows { Assert-OfficeWritablePath $file } 'not a directory'
}
# Regression: no product is registered, but C2R service/metadata survives.
# Exercise the real removal, readiness and installation functions together.
& {
$script:regressionInstalled=$false; $script:regressionCommands=@()
function Get-OfficeSuiteInventory { if ($script:regressionInstalled) { [pscustomobject]@{DisplayName='Click-to-Run: O365BusinessRetail'} } }
function Get-OfficeClickToRunState { [pscustomobject]@{Present=$true;SourceReferences=@('C:\Windows\SystemTemp\EmberkomOfficeDeployment\previous\ODT');WorkingConfiguration=@('orphaned-working-marker')} }
function Get-CimInstance { @() }
function Test-Path { $true }
function Get-ItemProperty { [pscustomobject]@{ProductReleaseIds='O365BusinessRetail';Platform='x64';VersionToReport='16.0.20326.20158'} }
function Invoke-OfficeScrubRecovery { throw 'Scrub must not run when no product is registered.' }
function Invoke-OfficeProcess {
param($FilePath,$Arguments,$LogPrefix)
$script:regressionCommands += $Arguments
Assert-OfficeTest ($Arguments -eq ('/configure "' + $media.Config + '"') -and (Split-Path -Leaf $LogPrefix) -eq 'office-install') 'Only the fresh installation configuration may run in the orphaned-service case.'
$script:regressionInstalled=$true
0
}
$media=[pscustomobject]@{Setup='inert-setup.exe';Config=(Join-Path $testRoot 'fresh-install.xml');Version='16.0.20326.20158'}
$options=[pscustomobject]@{OfficeArchitecture='64';ProductId='O365BusinessRetail';TargetOfficeVersion='16.0.20326.20158'}
Assert-OfficeTest ((Remove-OfficeSuite $media $testRoot) -eq 0) 'An orphaned service must skip removal even without a removal configuration.'
Assert-OfficeRemovalComplete $testRoot
Assert-OfficeTest ((Install-OfficeMedia $options $media $testRoot) -eq 0 -and $script:regressionCommands.Count -eq 1) 'The orphaned-service path must reach and verify the requested installation.'
}
# Inspect persisted state without touching the actual registry or Office service.
& {
function Test-Path { return $true }
function Get-Item { [pscustomobject]@{PSPath='fixture';Name='ClickToRun'} }
function Get-ChildItem { }
function Get-Service { [pscustomobject]@{Name='ClickToRunSvc'} }
function Get-ItemProperty { [pscustomobject]@{WorkingConfiguration='old-guid';SourcePath='C:\Windows\SystemTemp\EmberkomOfficeDeployment\old\ODT';Platform='x64'} }
$state = Get-OfficeClickToRunState
Assert-OfficeTest ($state.Present -and $state.WorkingConfiguration[0] -eq 'old-guid' -and $state.SourceReferences.Count -eq 1) 'Interrupted Click-to-Run configuration must be detected without installed products.'
function Get-CimInstance { @() }
function Get-OfficeSuiteInventory { @() }
Assert-OfficeTest (@(Assert-OfficeRemovalComplete $testRoot).Count -eq 0) 'Service, working markers and old source references alone must not block an otherwise idle installation.'
function Get-CimInstance { [pscustomobject]@{Name='setup.exe';ProcessId=123;CommandLine='setup.exe /configure remove.xml'} }
Assert-OfficeThrows { Assert-OfficeRemovalComplete $testRoot } 'workers are still running'
function Get-CimInstance { @() }
function Get-OfficeSuiteInventory { [pscustomobject]@{DisplayName='Registered C2R Office'} }
Assert-OfficeThrows { Assert-OfficeRemovalComplete $testRoot } 'products remain before replacement'
function Get-OfficeSuiteInventory { [pscustomobject]@{DisplayName='MSI Office';WindowsInstaller=1} }
Assert-OfficeTest (@(Assert-OfficeRemovalComplete $testRoot).Count -eq 0) 'Legacy MSI products remain assigned to RemoveMSI during installation.'
function Get-ItemProperty { [pscustomobject]@{Platform='x64'} }
$null = Assert-OfficeRemovalComplete
function Get-ItemProperty { throw 'Registry access denied' }
Assert-OfficeThrows { Assert-OfficeRemovalComplete } 'Registry access denied'
}
# Execute the real deferred action with only its live download replaced.
& {
$id='d'*32; $script:liveHelperId=$null
function New-Object {
param($TypeName)
Assert-OfficeTest ($TypeName -eq 'Net.WebClient') 'Deferred cleanup must fetch its helper live.'
$client=[pscustomobject]@{}
$client | Add-Member ScriptMethod DownloadString { param($Uri) '# EmberkomOfficeUserCleanup-v5' + [Environment]::NewLine + 'param($DeploymentId) $script:liveHelperId=$DeploymentId' }
$client | Add-Member ScriptMethod Dispose { }
$client
}
$command=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String((New-OfficeUserCleanupCommand $id)))
& ([scriptblock]::Create($command))
Assert-OfficeTest ($script:liveHelperId -eq $id -and !$command.Contains('-File ')) 'Deferred cleanup must execute freshly fetched source in memory with the correct deployment ID.'
}
# A new deployment clears every previous GUID workspace, including legacy caches,
# while preserving logs and refusing to race a previous installer or user task.
& {
$root=Join-Path $testRoot 'old-deployments'; $null=[IO.Directory]::CreateDirectory($root)
$old=Join-Path $root ('e'*32); $null=[IO.Directory]::CreateDirectory((Join-Path $old 'ODT'))
$legacyMetadata=Join-Path $testRoot ('OfficeReleaseHistory-' + ('e'*32) + '.html'); Set-Content -LiteralPath $legacyMetadata -Value 'abandoned metadata'
foreach ($name in @('ODT\payload.dat','ODT\native.log','install.xml','remove.xml','options.json','media-cache.json','Office-UserCleanup.ps1','user-cleanup.lock','reinstall-started','result.log')) { Set-Content -LiteralPath (Join-Path $old $name) -Value 'old content, not reusable' }
$unknown=Join-Path $root 'unrelated'; $null=[IO.Directory]::CreateDirectory($unknown); Set-Content -LiteralPath (Join-Path $unknown 'keep.txt') -Value 'untouched'
function Get-OfficeDeploymentRoots { $root }
$script:oldInstaller=$false; $script:oldTaskState='Running'; $script:oldTaskRemoved=$false
function Get-CimInstance { if ($script:oldInstaller) { [pscustomobject]@{Name='OfficeClickToRun.exe';CommandLine='OfficeClickToRun.exe platform=x64'} } }
function Get-ScheduledTask { if (!$script:oldTaskRemoved) { [pscustomobject]@{TaskName="Emberkom-OfficeCleanup-$('e'*32)-S-1-5-21-123";TaskPath='\';State=$script:oldTaskState} } }
function Disable-ScheduledTask { Assert-OfficeTest ($script:oldTaskState -eq 'Ready') 'Only idle tasks may be retired.' }
function Unregister-ScheduledTask { $script:oldTaskRemoved=$true }
Assert-OfficeThrows { Clear-OfficePreviousDeploymentFiles } 'user cleanup is still running'
Assert-OfficeTest (Test-Path -LiteralPath (Join-Path $old 'ODT\payload.dat')) 'Active user tasks must block old-cache cleanup.'
$script:oldTaskState='Ready'; $script:oldInstaller=$true
Assert-OfficeThrows { Clear-OfficePreviousDeploymentFiles } 'surviving installer'
$script:oldInstaller=$false
Clear-OfficePreviousDeploymentFiles
$remaining=@(Get-ChildItem -LiteralPath $old -Recurse -File)
Assert-OfficeTest ($script:oldTaskRemoved -and $remaining.Count -eq 2 -and @($remaining | Where-Object Extension -ne '.log').Count -eq 0) 'Previous cached downloads, options and scripts must be removed; nested logs must remain.'
Assert-OfficeTest (!(Test-Path -LiteralPath $legacyMetadata)) 'Abandoned legacy assessment metadata must be removed too.'
Assert-OfficeTest (Test-Path -LiteralPath (Join-Path $unknown 'keep.txt')) 'Cleanup must stay within GUID deployment folders.'
Clear-OfficePreviousDeploymentFiles
Assert-OfficeTest (@(Get-ChildItem -LiteralPath $old -Recurse -File).Count -eq 2) 'Cleanup must be repeatable with logs-only directories.'
}
# Cleanup runs synchronously on every install exit. Only logs survive in staging;
# pending-user tasks retain synchronization state but fetch their helper live.
& { & {
$root = Join-Path $testRoot 'temporary-downloads'; $null = [IO.Directory]::CreateDirectory($root) $root = Join-Path $testRoot 'temporary-downloads'; $null = [IO.Directory]::CreateDirectory($root)
$workspace = Join-Path $root ('c' * 32); $null = [IO.Directory]::CreateDirectory($workspace) $workspace = Join-Path $root ('c' * 32); $null = [IO.Directory]::CreateDirectory($workspace)
@@ -929,7 +1291,7 @@ try {
} }
$media = [pscustomobject]@{Helper=(Join-Path $workspace 'Office-UserCleanup.ps1')} $media = [pscustomobject]@{Helper=(Join-Path $workspace 'Office-UserCleanup.ps1')}
$userWorkspace = New-OfficeUserWorkspace $media $workspace $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 (!(Test-Path -LiteralPath (Join-Path $userWorkspace 'Office-UserCleanup.ps1')) -and (Test-Path -LiteralPath (Join-Path $userWorkspace 'user-cleanup.lock'))) 'Pending tasks must retain only synchronization state, never cached code.'
$script:cleanupTasks = $true; $script:cleanupProcess = $true $script:cleanupTasks = $true; $script:cleanupProcess = $true
function Get-CimInstance { if ($script:cleanupProcess) { [pscustomobject]@{CommandLine="setup.exe $workspace\install.xml"} } } 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 Get-ScheduledTask { if ($script:cleanupTasks) { [pscustomobject]@{TaskName="Emberkom-OfficeCleanup-$('c' * 32)-SID"; State='Ready'} } }
@@ -938,16 +1300,25 @@ try {
Assert-OfficeTest ($warnings.Count -and (Test-Path -LiteralPath (Join-Path $workspace 'ODT'))) 'Cleanup deleted files referenced by a surviving installer.' Assert-OfficeTest ($warnings.Count -and (Test-Path -LiteralPath (Join-Path $workspace 'ODT'))) 'Cleanup deleted files referenced by a surviving installer.'
$script:cleanupProcess = $false $script:cleanupProcess = $false
$warnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace $warnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace
Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath $workspace)) 'Successful deployment left its temporary workspace behind.' 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 cache cleanup deleted the pending-user helper.' Assert-OfficeTest (!(Test-Path -LiteralPath $media.Helper) -and @(Get-ChildItem -LiteralPath $workspace -File | Where-Object Extension -ne '.log').Count -eq 0) 'Deployment cleanup must leave only log files.'
Assert-OfficeTest (Test-Path -LiteralPath (Join-Path $userWorkspace 'user-cleanup.lock')) 'Pending-user synchronization state must survive staging cleanup.'
$script:cleanupTasks = $false $script:cleanupTasks = $false
$warnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace $warnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace
Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath $userWorkspace)) 'Completed user cleanup left its helper folder behind.' 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. # An installer without a source path, locked media and links all defer cleanup.
$legacy = Join-Path $userRoot ('d' * 32); $null = [IO.Directory]::CreateDirectory($legacy) Assert-OfficeTest (Test-OfficeStagingInUse $workspace @([pscustomobject]@{Name='OfficeC2RClient.exe'})) 'Surviving native installers must defer media cleanup.'
foreach ($name in @('options.json','odt.exe','Office-UserCleanup.ps1','user-cleanup.lock')) { Set-Content -LiteralPath (Join-Path $legacy $name) -Value 'fixture' } Assert-OfficeThrows { Remove-OfficeManagedItem $root $testRoot } 'outside the Office deployment root'
$warnings = Complete-OfficeDeploymentFiles $workspace -PreviousRoot $userRoot Assert-OfficeThrows { Remove-OfficeManagedItem $root $root } 'outside the Office deployment root'
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.' $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. # The legacy uninstaller must delete both successful and partial downloads.
& { & {
@@ -973,22 +1344,35 @@ try {
throw "Unexpected object requested by orchestration fixture: $TypeName" throw "Unexpected object requested by orchestration fixture: $TypeName"
} }
function Assert-OfficeDeploymentHost { } function Assert-OfficeDeploymentHost { }
function Assert-OfficeDiskSpace { param($Workspace,[switch]$DownloadingMedia) if ($script:mode -eq 'disk-space') { throw 'Insufficient disk space after staging' } } function Assert-OfficeWritablePath { param($Path) [pscustomobject]@{Path=$Path} }
function Complete-OfficeDeploymentFiles { param($Workspace,$UserWorkspace,$PreviousRoot) $script:artifactCleanupRuns++; if ($script:mode -eq 'cleanup-warning') { return ,@('Synthetic file in use') }; return ,@() } function Test-OfficeDownloadLinks { [pscustomobject]@{StatusCode=200;Method='HEAD'} }
function Get-OfficeClickToRunState { [pscustomobject]@{Present=$false;SourceReferences=@();WorkingConfiguration=@()} }
function Clear-OfficePreviousDeploymentFiles { if ($script:mode -eq 'old-cache') { throw 'Previous artifacts are locked' }; $script:priorCleanupRuns++ }
function Assert-OfficeRemovalComplete { if ($script:mode -eq 'readiness-error') { throw 'Removal verification failed' } }
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 New-OfficeUserWorkspace { param($Media,$Workspace) $Workspace }
function Register-ScheduledTask { throw 'Unexpected task registration in orchestration fixture.' } 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 Start-Transcript { }
function Stop-Transcript { } function Stop-Transcript { }
function Get-CimInstance { [pscustomobject]@{SID='S-1-5-21-test'; LocalPath=$profile; Special=$false} } function Get-CimInstance { [pscustomobject]@{SID='S-1-5-21-test'; LocalPath=$profile; Special=$false} }
Set-Content -LiteralPath (Join-Path $profile 'NTUSER.DAT') -Value 'test hive, never loaded' Set-Content -LiteralPath (Join-Path $profile 'NTUSER.DAT') -Value 'test hive, never loaded'
function Stop-OfficeDeploymentApps { $script:events += 'apps' } function Stop-OfficeDeploymentApps { $script:events += 'apps' }
function Get-OfficeRunningApps { } function Get-OfficeRunningApps { }
function Get-OfficeSuiteInventory { if ($script:mode -ne 'office-reboot' -or $script:removalStillRegistered) { [pscustomobject]@{DisplayName='Synthetic Office'} } } function Get-OfficeSuiteInventory { if ($script:mode -notin @('office-reboot','scrub-recovery') -or $script:removalStillRegistered) { [pscustomobject]@{DisplayName='Synthetic Office'} } }
function Get-OfficeMachineCompanionEntries { if ($script:removalStillRegistered) { [pscustomobject]@{DisplayName='Synthetic OneDrive'} } } 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-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 Remove-OfficeSuite {
param($Media,$Workspace)
$script:events += 'remove-office'
if ($script:mode -eq 'remove-office') { throw 'Office removal failure' }
if ($script:mode -eq 'scrub-recovery') { $Media | Add-Member ScrubAttempted $true; $Media | Add-Member ScrubReason 'fixture recovery'; return 3010 }
if ($script:mode -eq 'office-reboot') { return 3010 }
return 0
}
function Clear-OfficeProfileIdentity { $script:events += 'identity'; if ($script:mode -eq 'identity') { throw 'identity failure' } } function Clear-OfficeProfileIdentity { $script:events += 'identity'; if ($script:mode -eq 'identity') { throw 'identity failure' } }
function Start-OfficeUserCleanup { function Start-OfficeUserCleanup {
$script:events += 'user'; if ($script:mode -eq 'user') { throw 'user still running' } $script:events += 'user'; if ($script:mode -eq 'user') { throw 'user still running' }
@@ -1002,7 +1386,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'}} } 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 $script:removalStillRegistered=$false
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'; DeferReboot='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','readiness-error','identity','user','phase','install','install-companions','pending','reboot','office-reboot','companion-reboot')) {
$script:artifactCleanupRuns = 0 $script:artifactCleanupRuns = 0
$script:events = @(); $errorResult = $null; $result = $null $script:events = @(); $errorResult = $null; $result = $null
try { $result = Invoke-OfficeDeployment $options } catch { $errorResult = $_ } try { $result = Invoke-OfficeDeployment $options } catch { $errorResult = $_ }
@@ -1013,19 +1397,34 @@ try {
} else { Assert-OfficeTest ($null -ne $errorResult) "Failure swallowed in $script:mode" } } 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','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 -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.' } 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 '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.' } 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 foreach ($deferScrub in @('true','false')) {
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Insufficient disk space after staging' $script:mode='scrub-recovery'; $script:events=@()
Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Validation must not report success or mutate apps with insufficient installation space.' $options=Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium';OfficeAppShutdown='Force';ValidateBeforeChanges='false';DeferReboot=$deferScrub}
$result=Invoke-OfficeDeployment $options
Assert-OfficeTest ($result.ExitCode -eq 3010 -and $result.ScrubRecoveryAttempted -and $result.ScrubRecoveryReason -eq 'fixture recovery') 'Scrub recovery and restart requirement must be visible in the final receipt.'
if ($deferScrub -eq 'true') { Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'Installed' -and 'install' -in $script:events) 'Verified scrub may continue installation when reboot is deferred.' }
else { Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'RestartRequiredBeforeInstall' -and 'install' -notin $script:events -and 'identity' -notin $script:events) 'Nondeferred scrub restart must stop before replacement installation and user cleanup.' }
}
$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 $options.ValidateBeforeChanges=$false
$script:mode='cleanup-warning'; $script:events=@() $script:mode='cleanup-warning'; $script:events=@()
$result = @(Invoke-OfficeDeployment $options) $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.' Assert-OfficeTest ($result.Count -eq 1 -and $result[0].ArtifactCleanupPending -and $result[0].ExitCode -eq 2 -and $result[0].OfficeDeploymentStatus -eq 'InstalledWithArtifactCleanupPending') 'Unremoved artifacts must report partial completion instead of clean success.'
$script:mode='old-cache'; $script:events=@(); $script:workspaceCreates=0
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Previous artifacts are locked'
Assert-OfficeTest ($script:events.Count -eq 0 -and $script:workspaceCreates -eq 0) 'Old artifacts must be cleared before creating or downloading a new deployment.'
foreach ($script:mode in @('registration','registration-and-pending','registration-reboot')) { foreach ($script:mode in @('registration','registration-and-pending','registration-reboot')) {
$script:events=@(); $script:artifactCleanupRuns=0 $script:events=@(); $script:artifactCleanupRuns=0
function Install-OfficeMedia { $script:events += 'install'; if ($script:mode -eq 'registration-reboot') { return 3010 }; return 0 } function Install-OfficeMedia { $script:events += 'install'; if ($script:mode -eq 'registration-reboot') { return 3010 }; return 0 }
@@ -1056,12 +1455,12 @@ try {
Assert-OfficeTest (!$result.RestartRequired -and $result.ExitCode -eq 0) 'A clean deployment without restart requests must not demand a restart.' 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 ($shutdown in @('Abort','Force')) {
foreach ($validate in @($null, '', 'true')) { foreach ($validate in @($null, '', 'true')) {
$script:events=@() $script:events=@(); $script:workspaceCreates=0; $script:artifactCleanupRuns=0; $script:priorCleanupRuns=0
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeAppShutdown=$shutdown; ValidateBeforeChanges=$validate} $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeAppShutdown=$shutdown; ValidateBeforeChanges=$validate}
$result = Invoke-OfficeDeployment $options $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.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 ($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 $script:priorCleanupRuns -eq 0 -and !$result.MediaDownloaded -and !$result.Workspace -and !$result.MetadataResolved) '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.' Assert-OfficeTest (!$result.TeamsSelected -and $result.ProfileCount -eq 1 -and $result.ExistingOffice[0] -eq 'Synthetic Office') 'Validation report lost the deployment plan.'
} }
} }
@@ -1069,13 +1468,16 @@ try {
$script:events=@() $script:events=@()
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'} $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'}
$result = Invoke-OfficeDeployment $options $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=@() $options.OfficeAppShutdown='Abort'; $script:events=@()
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Apps are running' Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Apps are running'
Assert-OfficeTest ($script:events.Count -eq 0) 'Validation did not stop on an Abort prerequisite failure.' Assert-OfficeTest ($script:events.Count -eq 0) 'Validation did not stop on an Abort prerequisite failure.'
$options.OfficeAppShutdown='Force'; $script:mode='download'; $script:events=@() $options.OfficeAppShutdown='Force'; $script:mode='release'; $script:events=@()
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'download failure' $result = Invoke-OfficeDeployment $options
Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Failed validation reached mutations.' Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'ValidationPassed' -and !$result.MetadataResolved) 'Assessment must not request release metadata.'
$options.ValidateBeforeChanges=$false
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Release metadata unavailable'
Assert-OfficeTest ($script:events.Count -eq 0) 'Failed release resolution reached media downloads or app removal.'
$options.ValidateBeforeChanges='false' $options.ValidateBeforeChanges='false'
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'validated Boolean' Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'validated Boolean'
$options.ValidateBeforeChanges=$false; $options.DeferReboot='false'; $script:events=@() $options.ValidateBeforeChanges=$false; $options.DeferReboot='false'; $script:events=@()
@@ -1166,8 +1568,10 @@ __LAUNCH__
Assert-OfficeTest ($probeExitCode -eq $case.Code) "Shim did not propagate workload exit $($case.Code): $probeOutput" Assert-OfficeTest ($probeExitCode -eq $case.Code) "Shim did not propagate workload exit $($case.Code): $probeOutput"
$probeText = $probeOutput | Out-String $probeText = $probeOutput | Out-String
if ($case.Mode -eq 'success') { if ($case.Mode -eq 'success') {
Assert-OfficeTest ($probeText.IndexOf('{') -ge 0) "Main workload receipt is missing from shim output: $probeText" # Temp/log paths can contain GUID braces; locate the JSON object's line.
$receipt = $probeText.Substring($probeText.IndexOf('{')) | ConvertFrom-Json $receiptStart = [regex]::Match($probeText, '(?m)^\s*\{\s*\r?$')
Assert-OfficeTest $receiptStart.Success "Main workload receipt is missing from shim output: $probeText"
$receipt = $probeText.Substring($receiptStart.Index) | ConvertFrom-Json
Assert-OfficeTest ($receipt.ProductId -eq 'O365ProPlusEEANoTeamsRetail' -and $receipt.Company -ceq $probeValues.COMPANY -and $receipt.Activation -eq 'SharedComputer') 'Shim lost injected strings before main workload.' Assert-OfficeTest ($receipt.ProductId -eq 'O365ProPlusEEANoTeamsRetail' -and $receipt.Company -ceq $probeValues.COMPANY -and $receipt.Activation -eq 'SharedComputer') 'Shim lost injected strings before main workload.'
Assert-OfficeTest ($receipt.ValidateBeforeChanges -eq ($case.Validate -ne 'false')) 'Shim lost the validation gate.' Assert-OfficeTest ($receipt.ValidateBeforeChanges -eq ($case.Validate -ne 'false')) 'Shim lost the validation gate.'
Assert-OfficeTest ($receipt.DeferReboot -is [bool] -and !$receipt.DeferReboot) 'Shim/main entry lost or misparsed the injected false restart string.' Assert-OfficeTest ($receipt.DeferReboot -is [bool] -and !$receipt.DeferReboot) 'Shim/main entry lost or misparsed the injected false restart string.'
@@ -1208,8 +1612,11 @@ exit $resultCode
'@ '@
$nativeProbePath = Join-Path $testRoot 'host-probe.ps1'; Set-Content -LiteralPath $nativeProbePath -Value $nativeProbeTemplate.Replace('__ENTRY__', $entryText) $nativeProbePath = Join-Path $testRoot 'host-probe.ps1'; Set-Content -LiteralPath $nativeProbePath -Value $nativeProbeTemplate.Replace('__ENTRY__', $entryText)
$x86PowerShell = Join-Path $env:WINDIR 'SysWOW64\WindowsPowerShell\v1.0\powershell.exe' $x86PowerShell = Join-Path $env:WINDIR 'SysWOW64\WindowsPowerShell\v1.0\powershell.exe'
$ErrorActionPreference='Continue'
$hostOutput = & $x86PowerShell -NoProfile -ExecutionPolicy Bypass -File $nativeProbePath 2>&1 $hostOutput = & $x86PowerShell -NoProfile -ExecutionPolicy Bypass -File $nativeProbePath 2>&1
Assert-OfficeTest ($LASTEXITCODE -eq 2) '32-bit Syncro host lost the native-host exit code.' $hostExitCode = $LASTEXITCODE
$ErrorActionPreference='Stop'
Assert-OfficeTest ($hostExitCode -eq 2) '32-bit Syncro host lost the native-host exit code.'
$hostText = $hostOutput | Out-String $hostText = $hostOutput | Out-String
Assert-OfficeTest ($hostText -match 'Native host probe' -and $hostText -notmatch 'CLIXML') 'Native host messages must remain readable in Syncro.' Assert-OfficeTest ($hostText -match 'Native host probe' -and $hostText -notmatch 'CLIXML') 'Native host messages must remain readable in Syncro.'
$hostResult = $hostText.Substring($hostText.IndexOf('{')) | ConvertFrom-Json $hostResult = $hostText.Substring($hostText.IndexOf('{')) | ConvertFrom-Json
+232 -11
View File
@@ -30,11 +30,39 @@ function New-CleanupFixture {
try { try {
$core = Read-CleanupAst 'Start-SystemCleanup.ps1' $core = Read-CleanupAst 'Start-SystemCleanup.ps1'
$shim = Read-CleanupAst 'rmm/Start-SystemCleanup.ps1' $shim = Read-CleanupAst 'rmm/Start-SystemCleanup.ps1'
Assert-Cleanup ($core.Extent.Text -notmatch '(?i)AnalyzeComponentStore|dism\.exe') 'Reports must not ship a DISM analysis invocation.'
foreach ($definition in $core.FindAll({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst]}, $false)) { foreach ($definition in $core.FindAll({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst]}, $false)) {
. ([scriptblock]::Create($definition.Extent.Text)) . ([scriptblock]::Create($definition.Extent.Text))
} }
$script:messages = @() # Never contend with a real deployment on the test host.
function Write-SystemCleanupMessage { param($Message) $script:messages += $Message } function New-SystemCleanupOfficeMutex { return [Threading.Mutex]::new($false) }
$messageWriter = ${function:Write-SystemCleanupMessage}
$script:messages = @(); $script:details = @()
function Write-SystemCleanupMessage {
param($Message, [switch]$Detail)
if ($Detail) { $script:details += $Message } else { $script:messages += $Message }
}
& {
$VerbosePreference = 'SilentlyContinue'
$visible = @(& $messageWriter 'compact output' 6>&1)
$hidden = @(& $messageWriter 'handler inventory' -Detail 4>&1 6>&1)
Assert-Cleanup ($visible.Count -eq 1 -and [string]$visible[0] -match 'compact output' -and $hidden.Count -eq 0) 'Verbose diagnostics must not consume the normal RMM output budget.'
$VerbosePreference = 'Continue'
$verbose = @(& $messageWriter 'handler inventory' -Detail 4>&1)
Assert-Cleanup ($verbose.Count -eq 1 -and $verbose[0] -is [Management.Automation.VerboseRecord]) 'Full diagnostics must remain available on the verbose stream.'
}
& {
# Run the actual entry statement with an inert function. The host summary
# must survive, while success-stream objects must not become a second report.
function Invoke-SystemCleanup {
param($Options)
Write-SystemCleanupMessage 'entry summary'
[pscustomobject]@{Category='Fixture'; Enabled=$true; CandidateFiles=1}
}
$script:messages = @()
$output = @(& ([scriptblock]::Create($core.EndBlock.Statements[-1].Extent.Text)))
Assert-Cleanup ($output.Count -eq 0 -and $script:messages -contains 'entry summary') 'Core entry must suppress the duplicate object dump without suppressing the summary.'
}
function New-CleanupContext { function New-CleanupContext {
param([bool]$ReportOnly = $true, [bool]$Server = $false) param([bool]$ReportOnly = $true, [bool]$Server = $false)
return @{ return @{
@@ -183,7 +211,7 @@ try {
$o.ReportOnly=$true $o.ReportOnly=$true
foreach ($name in $blocked) { if ($name -ne 'DiskCleanup') { $o[$name]=$true } } foreach ($name in $blocked) { if ($name -ne 'DiskCleanup') { $o[$name]=$true } }
$result = @(Invoke-SystemCleanup $o) $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.' Assert-Cleanup (@($script:assessed | Where-Object { $_ -in $blocked }).Count -eq 0) 'Server report must not assess blocked categories.'
} }
@@ -214,17 +242,185 @@ try {
function Get-ChildItem { throw 'None must not access the registry.' } function Get-ChildItem { throw 'None must not access the registry.' }
function Test-SystemCleanupAppRunning { throw 'None must not probe native cleanup.' } function Test-SystemCleanupAppRunning { throw 'None must not probe native cleanup.' }
function Invoke-SystemCleanupProcess { throw 'None must not launch cleanmgr.' } function Invoke-SystemCleanupProcess { throw 'None must not launch cleanmgr.' }
$script:messages = @() $script:messages = @(); $script:details = @()
Invoke-SystemCleanupCategory $c 'DiskCleanup' { Invoke-SystemCleanupDiskCleanup $c } Invoke-SystemCleanupCategory $c 'DiskCleanup' { Invoke-SystemCleanupDiskCleanup $c }
Write-SystemCleanupReport $c Write-SystemCleanupReport $c
$report = $script:messages -join "`n" $report = $script:messages -join "`n"
Assert-Cleanup ($report -match '(?s)DISABLED -.*DiskCleanup \[CleanupDiskCleanupItems=None\].*No handlers selected') 'None must appear in the disabled report section with a clear explanation.' Assert-Cleanup ($report -match '(?s)DISABLED -.*DiskCleanup\s+-\s+-\s+.*None \(0 handlers\); will not run') 'None must appear in the disabled report section with a clear explanation.'
Assert-Cleanup ($report -match 'items not selected.*Previous Installations' -and $report -notmatch 'CleanupDiskCleanup=') 'None should report unselected handlers without advertising the removed boolean.' Assert-Cleanup (($script:details -join "`n") -match 'items not selected.*Previous Installations' -and $report -notmatch 'Previous Installations|CleanupDiskCleanup=') 'Unselected handler inventories belong in verbose diagnostics, not the compact report.'
$c.Options.ReportOnly = $false $c.Options.ReportOnly = $false
Invoke-SystemCleanupDiskCleanup $c Invoke-SystemCleanupDiskCleanup $c
Assert-Cleanup ($c.Errors -eq 0) 'None must not attempt native cleanup, even through the helper directly.' Assert-Cleanup ($c.Errors -eq 0) 'None must not attempt native cleanup, even through the helper directly.'
} }
# Report diagnostics remain independent of enablement and never inflate savings.
& {
$script:fileReads=0; $script:storageReads=0; $script:diagnosticProcesses=0
function Start-Process { $script:diagnosticProcesses++; throw 'Report diagnostics must not launch native programs.' }
$script:hiberState='present'; $script:storageState='present'
$sourceId='\\?\Volume{11111111-1111-1111-1111-111111111111}\'
$otherId='\\?\Volume{22222222-2222-2222-2222-222222222222}\'
$script:storageTarget=$sourceId
function Get-Item {
param($LiteralPath)
$script:fileReads++
if ($script:hiberState -eq 'missing') { throw [Management.Automation.ItemNotFoundException]::new('fixture absent') }
if ($script:hiberState -eq 'denied') { throw [UnauthorizedAccessException]::new('fixture denied') }
[pscustomobject]@{Length=4GB; PSIsContainer=$false; Attributes=[IO.FileAttributes]::Hidden}
}
function Get-CimInstance {
param($ClassName)
$script:storageReads++
if ($script:storageState -eq 'denied') { throw 'Synthetic CIM access failure' }
if ($ClassName -eq 'Win32_Volume') {
[pscustomobject]@{DeviceID=$sourceId; DriveLetter=$env:SystemDrive}
[pscustomobject]@{DeviceID=$otherId; DriveLetter='Z:'}
} elseif ($ClassName -eq 'Win32_ShadowStorage' -and $script:storageState -ne 'empty') {
# Source as escaped WMI path; destination as embedded CIM-style object.
[pscustomobject]@{Volume='Win32_Volume.DeviceID="\\\\?\\Volume{11111111-1111-1111-1111-111111111111}\\"'; DiffVolume=[pscustomobject]@{DeviceID=$script:storageTarget}; UsedSpace=$(if ($script:storageState -eq 'invalid') { $null } else { 2GB }); AllocatedSpace=3GB}
[pscustomobject]@{Volume=[pscustomobject]@{DeviceID=$otherId}; DiffVolume=[pscustomobject]@{DeviceID=$otherId}; UsedSpace=99GB; AllocatedSpace=100GB}
}
}
$c=New-CleanupContext
foreach ($name in @('DisableHibernation','ShadowCopies','ComponentStore')) {
$c.Options[$name]=$false
Invoke-SystemCleanupCategory $c $name {}
}
$c.Diagnostics=Get-SystemCleanupDiagnostics $c
Assert-Cleanup ($c.Stats.DisableHibernation.UsageBytes -eq 4GB -and $c.Stats.ShadowCopies.UsageBytes -eq 2GB -and $c.Diagnostics.ComponentStore -match 'not analyzed;.*superseded updates.*substantial.*little/none') 'Disabled options must still receive usage measurements and an honest note about potential component-store savings.'
Assert-Cleanup ($c.Stats.ShadowCopies.UsageNote.EndsWith("stored on $env:SystemDrive") -and ($script:details -join "`n") -match '3,072.00 MiB allocated') 'VSS must select the system volume, label its storage location and leave allocation details in verbose output.'
$totals=Get-SystemCleanupReportTotals $c
Assert-Cleanup ($totals.EnabledBytes -eq 0 -and $totals.AdditionalDisabledBytes -eq 0 -and -not $c.Options.ShadowCopies -and $c.Errors -eq 0) 'Diagnostic usage is not reclaimable savings and must not enable cleanup.'
$script:messages=@()
Write-SystemCleanupReport $c
$report=$script:messages -join "`n"
Assert-Cleanup ($report -notmatch '\bHibernation:|ShadowStorage:' -and [regex]::Matches($report,'(?m)^ ComponentStore:').Count -eq 1) 'Hibernation and VSS must not produce separate diagnostic lines.'
Assert-Cleanup ($report -match 'DisableHibernation\s+-\s+4,096.00\s+file size; excluded from totals' -and $report -match 'ShadowCopies\s+-\s+2,048.00\s+VSS used; excluded from totals; newest retained') 'Measured usage must appear in the category MiB column with its meaning and exclusion from totals.'
Assert-Cleanup ($report -notmatch '(DisableHibernation|ShadowCopies).*not estimated|GiB|MiB allocated') 'Measured rows must not say not estimated or repeat allocation diagnostics.'
$c.Options.ComponentStore=$true
$d=Get-SystemCleanupDiagnostics $c
Assert-Cleanup ($script:diagnosticProcesses -eq 0 -and $d.ComponentStore -eq $c.Diagnostics.ComponentStore) 'Enabling component cleanup must not launch analysis or fabricate a measured recommendation in report mode.'
$script:storageTarget=$otherId
$null=Get-SystemCleanupDiagnostics $c
Assert-Cleanup ($c.Stats.ShadowCopies.UsageBytes -eq 2GB -and $c.Stats.ShadowCopies.UsageNote -match 'stored on Z:') 'Shadow storage on another drive must not be attributed to the system drive.'
$script:storageState='empty'; $script:hiberState='missing'
$d=Get-SystemCleanupDiagnostics $c
Assert-Cleanup ($c.Stats.DisableHibernation.UsageBytes -eq 0 -and $c.Stats.ShadowCopies.UsageBytes -eq 0) 'Absent hibernation or a missing shadow-storage association must measure zero bytes.'
$script:messages=@(); Write-SystemCleanupReport $c
$report=$script:messages -join "`n"
Assert-Cleanup ($report -match 'DisableHibernation\s+-\s+0.00\s' -and $report -match 'ShadowCopies\s+-\s+0.00\s' -and $report -notmatch 'hiberfil.sys not present|no shadow-storage association|\bHibernation:|ShadowStorage:') 'Absent usage must appear as zero MiB in the two rows without separate absence messages.'
$script:storageState='invalid'
$null=Get-SystemCleanupDiagnostics $c
Assert-Cleanup ($null -eq $c.Stats.ShadowCopies.UsageBytes -and $c.Stats.ShadowCopies.UsageNote -match 'unavailable') 'Missing VSS measurements must not become zero.'
$script:storageState='denied'; $script:hiberState='denied'
$d=Get-SystemCleanupDiagnostics $c
Assert-Cleanup ($null -eq $c.Stats.DisableHibernation.UsageBytes -and $null -eq $c.Stats.ShadowCopies.UsageBytes -and $c.Stats.DisableHibernation.UsageNote -match 'unavailable' -and $c.Stats.ShadowCopies.UsageNote -match 'unavailable' -and $d.ComponentStore -match 'not analyzed' -and $c.Errors -eq 0) 'Diagnostic failures must clear old measurements, preserve the component note and not fail reporting.'
$script:messages=@(); Write-SystemCleanupReport $c
$report=$script:messages -join "`n"
Assert-Cleanup ($report -match 'DisableHibernation\s+-\s+-\s+unavailable' -and $report -match 'ShadowCopies\s+-\s+-\s+unavailable') 'Failed inspections must display unknown size rather than zero MiB.'
$script:fileReads=0; $script:storageReads=0
$c=New-CleanupContext -Server $true
foreach ($name in @('DisableHibernation','ShadowCopies')) { Invoke-SystemCleanupCategory $c $name {} }
$d=Get-SystemCleanupDiagnostics $c
Assert-Cleanup ($script:fileReads -eq 0 -and $script:storageReads -eq 0 -and $script:diagnosticProcesses -eq 0 -and $null -eq $c.Stats.DisableHibernation.UsageBytes -and $null -eq $c.Stats.ShadowCopies.UsageBytes -and $d.Count -eq 1 -and $d.ComponentStore -match 'not analyzed') 'Server reports must block hibernation/VSS assessment and only note potential component-store savings.'
$script:messages=@(); Write-SystemCleanupReport $c
$report=$script:messages -join "`n"
Assert-Cleanup ($report -match 'DisableHibernation\s+-\s+-\s+not assessed' -and $report -match 'ShadowCopies\s+-\s+-\s+not assessed') 'Server-blocked rows must remain unassessed rather than showing zero usage.'
$c.Options.ReportOnly=$false
$d=Get-SystemCleanupDiagnostics $c
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. # File ages, literal brackets, nested fresh files, no changes in preview.
$root=Join-Path $testRoot 'temps' $root=Join-Path $testRoot 'temps'
$old=New-CleanupFixture 'temps\old[1].tmp' $old=New-CleanupFixture 'temps\old[1].tmp'
@@ -259,7 +455,8 @@ try {
$script:messages=@() $script:messages=@()
Write-SystemCleanupReport $c Write-SystemCleanupReport $c
$report=$script:messages -join "`n" $report=$script:messages -join "`n"
Assert-Cleanup ($report.IndexOf('ENABLED -') -lt $report.IndexOf('DISABLED -') -and $report.IndexOf('DuplicateDownloads [CleanupDuplicateDownloads=true]') -lt $report.IndexOf('DISABLED -') -and $report.IndexOf('DownloadedExecutables [CleanupDownloadedExecutables=false]') -gt $report.IndexOf('DISABLED -')) 'Enabled and disabled report groups are unclear or misplaced.' Assert-Cleanup ($report.IndexOf('ENABLED -') -lt $report.IndexOf('DISABLED -') -and $report.IndexOf('DuplicateDownloads') -lt $report.IndexOf('DISABLED -') -and $report.IndexOf('DownloadedExecutables') -gt $report.IndexOf('DISABLED -')) 'Enabled and disabled report groups are unclear or misplaced.'
Assert-Cleanup ($report.IndexOf('Known savings:') -lt $report.IndexOf('ENABLED -') -and $report -match 'Additional DISABLED' -and $report -match '<0.01') 'Unique totals must appear first and small nonzero candidates must remain visible.'
$c=New-CleanupContext -ReportOnly $false $c=New-CleanupContext -ReportOnly $false
$script:disabledRan=$false $script:disabledRan=$false
Invoke-SystemCleanupCategory $c 'DownloadedExecutables' { $script:disabledRan=$true; Clear-SystemCleanupTree $c 'DownloadedExecutables' $potentialRoot $cutoff -Include @('*.exe') } Invoke-SystemCleanupCategory $c 'DownloadedExecutables' { $script:disabledRan=$true; Clear-SystemCleanupTree $c 'DownloadedExecutables' $potentialRoot $cutoff -Include @('*.exe') }
@@ -445,14 +642,15 @@ try {
switch ($ClassName) { switch ($ClassName) {
Win32_OperatingSystem { [pscustomobject]@{ProductType=1; Caption='Fixture Client'} } Win32_OperatingSystem { [pscustomobject]@{ProductType=1; Caption='Fixture Client'} }
Win32_UserProfile { [pscustomobject]@{Special=$false; LocalPath=(Join-Path $previewRoot 'Users\Alice')} } Win32_UserProfile { [pscustomobject]@{Special=$false; LocalPath=(Join-Path $previewRoot 'Users\Alice')} }
Win32_Volume { [pscustomobject]@{DriveLetter=$env:SystemDrive; DeviceID='volume1'} } Win32_Volume { [pscustomobject]@{DriveLetter=$env:SystemDrive; DeviceID='\\?\Volume{11111111-1111-1111-1111-111111111111}\'} }
Win32_ShadowCopy { Win32_ShadowCopy {
[pscustomobject]@{VolumeName='volume1'; InstallDate=[datetime]'2026-10-01'; ID='{11111111-1111-1111-1111-111111111111}'} [pscustomobject]@{VolumeName='\\?\Volume{11111111-1111-1111-1111-111111111111}\'; InstallDate=[datetime]'2026-10-01'; ID='{11111111-1111-1111-1111-111111111111}'}
[pscustomobject]@{VolumeName='volume1'; InstallDate=[datetime]'2026-10-02'; ID='{22222222-2222-2222-2222-222222222222}'} [pscustomobject]@{VolumeName='\\?\Volume{11111111-1111-1111-1111-111111111111}\'; InstallDate=[datetime]'2026-10-02'; ID='{22222222-2222-2222-2222-222222222222}'}
} }
} }
} }
function Test-SystemCleanupAppRunning { return $false } function Test-SystemCleanupAppRunning { return $false }
function Get-SystemCleanupOfficeStagingRoots { return (Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment') }
function Get-Service { [pscustomobject]@{Status='Stopped'} } function Get-Service { [pscustomobject]@{Status='Stopped'} }
function Remove-Item { throw 'PREVIEW MUTATION: Remove-Item' } function Remove-Item { throw 'PREVIEW MUTATION: Remove-Item' }
function New-ItemProperty { throw 'PREVIEW MUTATION: registry write' } function New-ItemProperty { throw 'PREVIEW MUTATION: registry write' }
@@ -462,21 +660,44 @@ try {
function Delete-DeliveryOptimizationCache { throw 'PREVIEW MUTATION: delivery cache' } function Delete-DeliveryOptimizationCache { throw 'PREVIEW MUTATION: delivery cache' }
function Start-Process { throw 'PREVIEW MUTATION: native program' } function Start-Process { throw 'PREVIEW MUTATION: native program' }
$o=Get-SystemCleanupOptions $o=Get-SystemCleanupOptions
$script:messages=@(); $script:details=@()
$result=@(Invoke-SystemCleanup $o) $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 '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 (@($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.' 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) "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)."
}
Assert-Cleanup ($compactOutput -notmatch 'Assessing |selected items:|items not selected|CandidateFiles\s*:' -and $compactOutput -match 'Standard \(7 handlers\)') 'Default output must show the preset without progress chatter, handler inventories, or object dumps.'
Assert-Cleanup (($script:details -join "`n") -match 'items not selected.*Previous Installations') 'Full handler details must remain available in verbose output.'
Assert-Cleanup ($compactOutput -match 'DisableHibernation\s+-\s+<0.01\s+file size' -and $compactOutput -match 'ShadowCopies\s+-\s+0.00\s+VSS used' -and $compactOutput -notmatch '\bHibernation:|ShadowStorage:' -and $compactOutput -match 'ComponentStore: not analyzed;.*superseded updates.*substantial.*little/none') 'Full entry-point report must show usage in category rows and retain the component note even with cleanup disabled.'
function Test-SystemCleanupAppRunning { return $true } function Test-SystemCleanupAppRunning { return $true }
function Get-Command { return $null } function Get-Command { return $null }
$o.DiskCleanupItems=@(); $o.DiskCleanupPreset='None' $o.DiskCleanupItems=@(); $o.DiskCleanupPreset='None'
$script:messages=@()
$result=@(Invoke-SystemCleanup $o) $result=@(Invoke-SystemCleanup $o)
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'RevitJournals' -and $_.Status -eq 'Skipped' }).Count -eq 1) 'An active application should skip cleanup, not fail the whole run.' Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'RevitJournals' -and $_.Status -eq 'Skipped' }).Count -eq 1) 'An active application should skip cleanup, not fail the whole run.'
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'DeliveryOptimization' -and -not $_.Enabled -and $_.Status -eq 'Unavailable' -and $null -eq $_.CandidateBytes }).Count -eq 1) 'A missing optional feature must be reported as unavailable, not zero savings or a failed report.' Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'DeliveryOptimization' -and -not $_.Enabled -and $_.Status -eq 'Unavailable' -and $null -eq $_.CandidateBytes }).Count -eq 1) 'A missing optional feature must be reported as unavailable, not zero savings or a failed report.'
$compactOutput=$script:messages -join "`n"
Assert-Cleanup ($compactOutput -match 'BrowserCache.*Partial; incomplete.*chrome.*msedge' -and $compactOutput -match 'RevitJournals.*Skipped.*Revit is running' -and $compactOutput -match 'DeliveryOptimization.*Unavailable.*not installed') 'Compacting output must preserve partial, skipped and unavailable reasons.'
} finally { } finally {
$env:SystemRoot=$savedEnvironment.SystemRoot; $env:SystemDrive=$savedEnvironment.SystemDrive; $env:ProgramData=$savedEnvironment.ProgramData $env:SystemRoot=$savedEnvironment.SystemRoot; $env:SystemDrive=$savedEnvironment.SystemDrive; $env:ProgramData=$savedEnvironment.ProgramData
} }
} }
& {
$c=New-CleanupContext
$script:messages=@(); $script:details=@()
Invoke-SystemCleanupCategory $c 'CrashDumps' { throw ("Synthetic failure`r`n" + ('long diagnostic ' * 300)) }
Write-SystemCleanupReport $c
$report=$script:messages -join "`n"
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 23-category preview: $script:compactReportBytes UTF-8 bytes."
Write-Host "PASS: $script:assertions offline cleanup assertions ($($PSVersionTable.PSVersion))." Write-Host "PASS: $script:assertions offline cleanup assertions ($($PSVersionTable.PSVersion))."
} finally { } finally {
# Only this test's generated directory; links are removed non-recursively above. # Only this test's generated directory; links are removed non-recursively above.
+210
View File
@@ -0,0 +1,210 @@
#Requires -Version 4.0
# Run with Windows PowerShell. All downloads, plan checks and installs are fixtures.
$ErrorActionPreference = 'Stop'
$repo = Split-Path -Parent $PSScriptRoot
$fixtureDir = Join-Path ([IO.Path]::GetTempPath()) ('CloudBackupTest-' + [guid]::NewGuid())
$null = New-Item -ItemType Directory -Path $fixtureDir
function Read-TestAst($Path) {
$parseErrors = $null
$tree = [Management.Automation.Language.Parser]::ParseFile($Path, [ref]$null, [ref]$parseErrors)
if ($parseErrors) { throw ($parseErrors | Out-String) }
return $tree
}
function Find-TestFunction($Tree, $Name) {
$fn = $Tree.Find({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $Name}, $false)
if (!$fn) { throw "Missing $Name" }
return $fn
}
try {
$core = Read-TestAst (Join-Path $repo 'Update-EmberkomCloudBackup.ps1')
$shim = Read-TestAst (Join-Path $repo 'rmm/Update-EmberkomCloudBackup.ps1')
foreach ($entry in @($shim,$core)) {
if ($entry.ScriptRequirements.RequiredPSVersion -ne [version]'4.0') { throw "Expected #Requires -Version 4.0 in $($entry.Extent.File)" }
}
$windowFn = Find-TestFunction $core 'Test-CloudBackupUpdateWindow'
. ([scriptblock]::Create($windowFn.Extent.Text))
foreach ($case in @(
@('23:30-00:30','23:30',$true), @('23:30-00:30','00:29',$true),
@('23:30-00:30','00:30',$false), @('12:00-13:00','11:59',$false),
@('12:00-13:00','12:00',$true), @('12:00-13:00','13:00',$false), @('','02:00',$true)
)) {
if ((Test-CloudBackupUpdateWindow $case[0] ([datetime]::ParseExact($case[1],'HH:mm',$null))) -ne $case[2]) {
throw "Window boundary failed for $($case[0]) at $($case[1])"
}
}
# Substitute only discovery of the installed product in the downloaded core.
$discovery = Find-TestFunction $core 'Get-CloudBackupInstallation'
$coreSource = $core.Extent.Text.Replace($discovery.Extent.Text, 'function Get-CloudBackupInstallation { Get-FixtureInstallation }')
$toolsAst = Read-TestAst (Join-Path $repo 'Tools.ps1')
$shimTools = (@('Run-Script','Get-EmberkomCloudBackupReleases','Get-EmberkomCloudBackupRelease','Save-EmberkomCloudBackupInstaller') |
ForEach-Object { (Find-TestFunction $toolsAst $_).Extent.Text }) -join [Environment]::NewLine
$fixtureBytes = [byte[]](1,2,3)
$sha = [Security.Cryptography.SHA256]::Create()
try { $hash = [BitConverter]::ToString($sha.ComputeHash($fixtureBytes)).Replace('-','') } finally { $sha.Dispose() }
$manifest = Get-Content -Raw -LiteralPath (Join-Path $repo 'resources/EmberkomCloudBackup.json') | ConvertFrom-Json
foreach ($kind in 'Windows','VM') {
if ($manifest.$kind.SHA256 -notmatch '^[a-f0-9]{64}$' -or $manifest.$kind.Url -notlike 'https://*') { throw "Bad $kind release" }
$manifest.$kind.SHA256 = $hash
$manifest.$kind.Version = '8.10.1.177'
}
function IsURLValid { param($URL) $true }
function Download-File {
param($URL)
if ($URL -notlike '*/Update-EmberkomCloudBackup.ps1') { throw "Unexpected script request" }
$path = Join-Path $fixtureDir 'downloaded.ps1'
[IO.File]::WriteAllText($path, $coreSource)
return $path
}
function New-Object {
param($TypeName,[object[]]$ArgumentList)
if ($TypeName -eq 'System.Threading.Mutex') {
return (Microsoft.PowerShell.Utility\New-Object -TypeName $TypeName -ArgumentList $ArgumentList)
}
if ($TypeName -ne 'Net.WebClient') { throw "Unexpected construction of $TypeName" }
$client = [pscustomobject]@{}
$client | Add-Member ScriptMethod DownloadString { param($url)
if ($url -like '*/Tools.ps1') { return $shimTools }
if ($url -like '*/Update-EmberkomCloudBackup.ps1') { return $coreSource }
if ($url -like '*/resources/EmberkomCloudBackup.json') {
$record.ManifestReads++
return ($manifest | ConvertTo-Json)
}
throw "Unexpected URL"
}
$client | Add-Member ScriptMethod Dispose {}
return $client
}
function Invoke-WebRequest {
param([switch]$UseBasicParsing,$Uri,$OutFile,$TimeoutSec,$ErrorAction)
$record.Downloads++
if ($Uri -cne $manifest.$kind.Url -or !$UseBasicParsing -or $TimeoutSec -ne 240) { throw 'Unexpected installer request' }
if (Test-Path -LiteralPath $OutFile) { throw 'Partial installer was not removed before retry' }
$record.Staged = $OutFile
[IO.File]::WriteAllBytes($OutFile, $fixtureBytes)
if ($scenario -eq 'corrupt') { [IO.File]::AppendAllText($OutFile,'x') }
if ($scenario -eq 'download failure') {
throw (Microsoft.PowerShell.Utility\New-Object Net.WebException -ArgumentList 'Certificate validation failed',([Net.WebExceptionStatus]::TrustFailure))
}
if ($scenario -eq 'persistent timeout' -or ($scenario -in @('timeout then success','plan during retry') -and $record.Downloads -eq 1)) {
throw (Microsoft.PowerShell.Utility\New-Object Net.WebException -ArgumentList 'The operation has timed out',([Net.WebExceptionStatus]::Timeout))
}
}
function Start-Sleep { param($Seconds) if ($Seconds -ne 3) { throw 'Unexpected retry delay' } }
function Get-FixtureInstallation {
if ($scenario -eq 'absent') { return }
$v = '8.9.1.177'
if ($scenario -in @('current','only VM newer','VM needs update','incomplete Windows')) { $v = '8.10.1.177' }
if ($record.Installs -and $scenario -ne 'unverified') { $v = $manifest.$kind.Version }
if ($scenario -eq 'newer') { $v = '8.11.0.1' }
if ($scenario -eq 'already updated' -and $record.Downloads) { $v = '8.10.1.177' }
[pscustomobject]@{ Version=[version]$v; Cli='Get-FixtureCli' }
}
function Get-FixtureCli($Command) {
if ($Command -ne 'ver') { throw 'Unexpected agent command' }
$record.CliCalls++
$global:LASTEXITCODE = 0
if ($kind -eq 'VM') { 'Backup Agent Edition: VMware' } else { 'Backup Agent Edition: DesktopIBB' }
'Service name: Fixture Service'
}
function Get-Date {
if ($scenario -eq 'window ended' -and $record.Downloads) { return [datetime]'2026-01-01T13:00' }
return [datetime]'2026-01-01T12:30'
}
function Get-CimInstance {
param($ClassName,$Filter,$Property,$ErrorAction)
$record.PlanChecks++
if ($ClassName -ne 'Win32_Process' -or $Filter -ne "Name = 'CBBackupPlan.exe'") { throw 'Unexpected worker query' }
if ($scenario -eq 'query failure') { throw 'Cannot enumerate processes' }
if ($scenario -eq 'busy' -or ($record.Downloads -and $scenario -in @('late plan','plan during retry'))) { [pscustomobject]@{ ProcessId=42 } }
}
function Start-Process {
param($FilePath,$ArgumentList,$WindowStyle,[switch]$Wait,[switch]$PassThru,$ErrorAction)
$record.Installs++
if ($FilePath -ne $record.Staged -or $ArgumentList -cne '/S' -or !$Wait -or !$PassThru) { throw 'Unexpected setup invocation' }
$code = switch ($scenario) { reboot {3010} failure {1603} default {0} }
[pscustomobject]@{ ExitCode=$code }
}
function Get-Service {
param($Name,$ErrorAction)
if ($Name -ne 'Fixture Service') { throw 'Unexpected service name' }
$service = [pscustomobject]@{}
$service | Add-Member ScriptMethod WaitForStatus { param($state,$timeout)
if ($state -ne 'Running' -or $scenario -eq 'service down') { throw 'Backup service unavailable' }
}
return $service
}
foreach ($case in @(
@('absent',0,0,0), @('current',0,0,0), @('newer',0,0,0),
@('only VM newer',0,0,0), @('VM needs update',0,1,1), @('incomplete Windows',1,0,0),
@('busy',0,0,0), @('late plan',0,1,0), @('query failure',1,0,0),
@('download failure',1,1,0), @('already updated',0,1,0), @('window ended',0,1,0),
@('timeout then success',0,2,1), @('plan during retry',0,2,0), @('persistent timeout',1,2,0),
@('bad window',1,0,0), @('corrupt',1,1,0), @('success',0,1,1),
@('VM',0,1,1), @('failure',1,1,1), @('unverified',1,1,1),
@('service down',1,1,1), @('reboot',3010,1,1)
)) {
$scenario,$expected,$expectedDownloads,$expectedInstalls = $case
$kind = if ($scenario -in @('VM','VM needs update')) { 'VM' } else { 'Windows' }
$manifest.VM.Version = if ($scenario -in @('only VM newer','VM needs update')) { '8.11.1.177' } else { '8.10.1.177' }
$manifest.Windows.SHA256 = if ($scenario -eq 'incomplete Windows') { '' } else { $hash }
$MSP360UpdateWindow = switch ($scenario) {
'bad window' { '25:00-26:00' }
'window ended' { '12:00-13:00' }
default { '' }
}
$record = @{ Downloads=0; Installs=0; Staged=$null; ManifestReads=0; CliCalls=0; PlanChecks=0 }
# PowerShell 4 writes Write-Host directly to the host. Capture it separately
# so log assertions work on 4.0 without mixing text into the core's return value.
$record.HostMessages = @()
$messages = & {
function Write-Host { param([string]$Object) $record.HostMessages += $Object }
& (Join-Path $repo 'rmm/Update-EmberkomCloudBackup.ps1') *>&1
}
$messages = @($messages) + $record.HostMessages
if ($LASTEXITCODE -ne $expected -or $record.Downloads -ne $expectedDownloads -or $record.Installs -ne $expectedInstalls) {
throw "$scenario failed. Exit=$LASTEXITCODE Downloads=$($record.Downloads) Installs=$($record.Installs). $messages"
}
if ($scenario -in @('current','newer','only VM newer')) {
$expectedCliCalls = if ($scenario -eq 'only VM newer') { 1 } else { 0 }
if ($record.ManifestReads -ne 1 -or $record.CliCalls -ne $expectedCliCalls -or $record.PlanChecks -ne 0 -or
($messages -join ' ') -notmatch 'No update needed') { throw "$scenario did not take the expected early exit" }
}
if ($record.Staged -and (Test-Path -LiteralPath $record.Staged)) { throw "$scenario left staged media" }
if ($scenario -eq 'persistent timeout') {
$output = $messages -join ' '
if ($output -notmatch 'attempt 2 of 2.*Timeout.*3 bytes saved' -or $output -match 'urlParams=') {
throw 'Persistent timeout must report the failed attempt and byte count without the signed URL.'
}
if (!$output.Contains($record.Staged) -or !$output.Contains($hash) -or
$output -notmatch "Z $([regex]::Escape($env:COMPUTERNAME)) - MSP360 installer download") {
throw 'Missing endpoint, UTC time, installer path or hash for endpoint security correlation.'
}
}
Write-Host "PASS $scenario"
}
# Check the provisioner's existing edition mapping at the new release-file boundary.
& {
function Import-MSP360Module {}
function Get-MBSAgent { $false }
function Get-EmberkomCloudBackupRelease($Build) {
$record.Selected = $Build
$record.AgentEdition = $AgentEdition
throw 'Stopped at release lookup'
}
foreach ($pair in @(@('desktop','Windows','desktop'), @('server','Windows','baremetal'), @('vm','VM','vmedition'))) {
$Edition = $pair[0]
$record = @{}
try { & (Join-Path $repo 'Install-EmberkomCloudBackup.ps1') }
catch { if ($_.Exception.Message -ne 'Stopped at release lookup') { throw } }
if ($record.Selected -ne $pair[1] -or $record.AgentEdition -ne $pair[2]) { throw "Wrong provisioning package for $Edition" }
Write-Host "PASS existing $Edition installer release selection"
}
}
} finally {
$fixtureCore = Join-Path $fixtureDir 'downloaded.ps1'
if (Test-Path -LiteralPath $fixtureCore) { Remove-Item -LiteralPath $fixtureCore -Force }
Remove-Item -LiteralPath $fixtureDir -Force
}
+8
View File
@@ -0,0 +1,8 @@
05:32:48 PM Information Created
Report: {
"ExecutionResult": "Failed",
"TroubleshooterName": "GH_OfficeUninstallALDA",
"Name": "Office Uninstall ALDA",
"ExecutionResultDetails": "There are no supported Office products installed.",
"DiagnosticName": "Utility-GetOfficeProducts"
}