Compare commits

..
17 Commits
Author SHA1 Message Date
dyoder 4e766357cc make the cloud backup update script require powershell 4 and make that the repo default for new scripts 2026-11-17 10:43:19 -05:00
dyoder 2bbb07c05e add retry logic to Cloud Backup download 2026-11-17 01:01:10 -05:00
dyoder bfdf8f5eae made the backup update script fail faster 2026-11-17 00:36:59 -05:00
dyoder 467f699103 add update script for cloud backup 2026-11-17 00:13:07 -05:00
dyoder f2830cb10a fix more issues with the scrubber and product install status 2026-10-30 15:35:38 -04:00
dyoder 0c614596f8 more fixes for scrubber 2026-10-29 17:05:00 -04:00
dyoder 597524fc13 more fixes for the scrubber 2026-10-29 16:17:45 -04:00
dyoder a8b8429b58 fix scrubber call 2026-10-29 15:24:01 -04:00
dyoder 52aa59a70c add scrubber back into deployment script 2026-10-29 15:05:37 -04:00
dyoder 3e24920646 update M365 deployment script to try not to depend on previous deployments 2026-10-29 14:29:37 -04:00
dyoder e2163a6158 adds OfficeStaging and SystemTemp 2026-10-23 12:25:00 -04:00
dyoder f9daec0542 validation check prereqs without staging/caching 2026-10-23 12:23:42 -04:00
dyoder 08dbb3cdd5 improve summary display 2026-10-23 11:33:03 -04:00
dyoder c5ef81dfca improve detection of space savings 2026-10-23 11:22:55 -04:00
dyoder ec9141d062 compact report output 2026-10-22 17:10:16 -04:00
dyoder e9fcc2f33b merge previous cleanup scripts into one Start-Cleanup.ps1 script 2026-10-22 16:58:12 -04:00
dyoder c8eec20391 add checks for free disk space 2026-10-22 16:57:31 -04:00
24 changed files with 4294 additions and 387 deletions
+79 -2
View File
@@ -2,6 +2,17 @@
## 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:
```powershell
@@ -14,8 +25,74 @@ The caller then invokes `Run-Script`, passing the repository script's filename w
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.
## 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'
$DNSHelperRequiredVersion = '2.3.0'
$DownloadRequired = $false
If (Test-Path $DNSHelper) {
$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
}
# SHA-256 of ekdns.exe from each v2.3.0 Windows release archive.
If ([Environment]::Is64BitOperatingSystem) {
$DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x64-exe/download/ekdns-x64.exe'
$DNSHelperHash = '308E36680C0E4AD7CE802F4B1D8C38E89B0D8E24BBCE4F33550721C78BA2224C'
} 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
If ($DownloadRequired) {
$DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x64-exe/download/ekdns-x64.exe'
If (!(Test-Path ${Env:ProgramFiles(x86)})) {
$DNSHelperURL = 'https://xfer.emberkom.com/shares/tools/folders/9b9988fb-c53a-4833-a4ad-68d01a3021bb/files/ekdns-x86-exe/download/ekdns-x86.exe'
$InstalledHash = (Get-FileHash -LiteralPath $DNSHelper -Algorithm SHA256 -ErrorAction SilentlyContinue).Hash
If ($InstalledHash -ne $DNSHelperHash) {
$StagedHelper = $DNSHelper + '.' + [guid]::NewGuid().ToString('N') + '.tmp'
Try {
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
@@ -62,15 +66,14 @@ If ( Test-Path $DNSHelper ) {
$commandString = """${DNSHelper}"" add -host ${HostString}"
$content = $RefreshScriptHeader + $commandString
Write-Output "Creating latest refresh script"
If ( Test-Path $RefreshScript ) { Remove-Item -Path $RefreshScript -Force }
Try {
New-Item -Path $RefreshScript -ItemType File -Force | Out-Null
Set-Content -Path $RefreshScript -Value $content
Set-Content -LiteralPath $RefreshScript -Value $content -Force -ErrorAction Stop
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 }
Write-Output "Updating local hosts file with name-to-IP mappings for the following host(s): ${HostString}"
& "${RefreshScript}"
Catch { Write-Error $_.Exception.Message ; Exit 1 }
} Else {
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
$ECB_WIN_URL = 'https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWTBzNG1zVDV0ckVMdStZVzBsam5uZklMVnZLeTBMVmxGNWt4VDhSMzNIL3VmK3VHNmxBVEZTQkxhMFhNR2ZuZzJCeE80MDJxVkRSWXdNa0dqSHdpbUN1bE01c3BWNFBVUmt2Q1c4endncjVZemFSSjEyYmFNL3hESHR2eWpVYXpBVlV2eU1kZVZFaEpvalk2Rk40Wk96UG9QdUwxYnZrRHREMmhLeTZoMW5Rbz0*&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4'
# Specify URL to "Backup Virtual Machine Edition" agent installer
$ECB_VMM_URL = 'https://console.msp360.com/api/build/download?urlParams=OEFsMzhldm1SbjhaSDhBc2VtYkpUREM3Y2pJSzg0REU4dkVtR1pHREkxMGFFUk9qZXJnSXk5SUF0ei8wZlZOWUpYM2xDY3ErMkpOVGpuWTRISDNFcFRFdWRibDgvTm8vUDhpWndON3kzaHNwOTFVa3h6WUdoeVVod1JmT2lRQ1FlVTE3Y0pnUncwSEJwS3FFcDBmTWt3cEdnSy9YemRsSTRiQWJHNi96cUtWbzZsc25QVllaR1QyQ21VVS95dFFVTkNndXdPVStGQXBIT0FZb2FIUzFuZy9mMU5qZUd5emhab1hFYjZWODB4ND0*&brandId=fb8308e2-448a-4645-a5f6-a3632a7e57f4'
# 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 update use the same published Emberkom packages.
switch ($Edition) {
'server' { $CloudBackupBuild = 'Windows'; $AgentEdition = 'baremetal' }
'vm' { $CloudBackupBuild = 'VM'; $AgentEdition = 'vmedition' }
default { $CloudBackupBuild = 'Windows'; $AgentEdition = 'desktop' }
}
# Install and import additional Powershell module
@@ -21,30 +14,9 @@ If ( $(Get-MBSAgent -ErrorAction SilentlyContinue) ) {
Return
}
#
# 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
#
# 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
#
$CloudBackupRelease = Get-EmberkomCloudBackupRelease -Build $CloudBackupBuild
$Installer = Join-Path (Get-TempPath) ("EmberkomCloudBackup-{0}.exe" -f [guid]::NewGuid())
Save-EmberkomCloudBackupInstaller -Release $CloudBackupRelease -Path $Installer
# Install the agent
Write-Output "Installing Emberkom Cloud Backup agent"
File diff suppressed because it is too large Load Diff
+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.
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 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.
## 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
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
@@ -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.
## 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
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\Download-File.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
```
+952
View File
@@ -0,0 +1,952 @@
#Requires -Version 5.1
<#
.SYNOPSIS
Retention-aware cleanup for Windows workstations and servers.
.DESCRIPTION
Reads Cleanup* variables from the calling scope (including the RMM Run-Script
dot-source scope). Missing variables use Get-SystemCleanupDefaults. No param()
block deliberately: RMM variables must not be overwritten by parameter defaults.
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
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.
#>
function Get-SystemCleanupDefaults {
return [ordered]@{
CleanupReportOnly = $true
CleanupTempDays = 7
CleanupDiagnosticDays = 30
CleanupBackupDays = 30
CleanupSystemTemp = $true
CleanupOfficeStaging = $true
CleanupUserTemp = $true
CleanupServiceTemp = $true
CleanupCBSArchives = $true
CleanupActiveCBSLog = $false
CleanupCrashDumps = $true
CleanupWERArchives = $true
CleanupAutodeskInstallers = $false
CleanupRecycleBin = $false
CleanupDisableHibernation = $false
CleanupCompactSearch = $false
CleanupShadowCopies = $false
CleanupDownloadedExecutables = $false
CleanupDuplicateDownloads = $false
CleanupOutlookBackups = $false
CleanupITunesBackups = $false
CleanupAppleDownloads = $false
CleanupBrowserCache = $false
CleanupRevitJournals = $true
CleanupDeliveryOptimization = $false
CleanupComponentStore = $false
CleanupDiskCleanupItems = 'Standard'
}
}
function Get-SystemCleanupHandlers {
# Every VolumeCaches handler from Start-Cleanup.ps1, including disabled ones.
return @(
'Downloaded Program Files', 'Internet Cache Files', 'Offline Pages Files',
'Recycle Bin', 'Temporary Files', 'Thumbnail Cache', 'User file versions',
'Active Setup Temp Folders', 'BranchCache', 'Memory Dump Files',
'Old ChkDsk Files', 'RetailDemo Offline Content', 'System error memory dump files',
'System error minidump files', 'Temporary Setup Files', 'Windows Defender',
'Windows Error Reporting Archive Files', 'Windows Error Reporting Queue Files',
'Windows Error Reporting System Archive Files', 'Windows Error Reporting System Queue Files',
'Windows Error Reporting Temp Files', 'Service Pack Cleanup', 'Update Cleanup',
'Upgrade Discarded Files', 'Windows Upgrade Log Files', 'Previous Installations',
'Setup Log Files', 'Windows ESD installation files', 'Content Indexer Cleaner',
'Delivery Optimization Files', 'Device Driver Packages', 'GameNewsFiles',
'GameStatisticsFiles', 'GameUpdateFiles', 'Temporary Sync Files'
)
}
function Get-SystemCleanupDiskCleanupPresets {
$standard = @(
'Downloaded Program Files', 'Internet Cache Files', 'Thumbnail Cache',
'Active Setup Temp Folders', 'Temporary Setup Files', 'Windows Defender',
'RetailDemo Offline Content'
)
$updates = @('Service Pack Cleanup', 'Update Cleanup', 'Upgrade Discarded Files', 'Windows Upgrade Log Files')
$diagnostics = @(
'Memory Dump Files', 'Old ChkDsk Files', 'System error memory dump files',
'System error minidump files', 'Setup Log Files',
'Windows Error Reporting Archive Files', 'Windows Error Reporting Queue Files',
'Windows Error Reporting System Archive Files', 'Windows Error Reporting System Queue Files',
'Windows Error Reporting Temp Files'
)
return [ordered]@{
Standard = $standard
StandardAndUpdates = @($standard + $updates)
StandardUpdatesAndDiagnostics = @($standard + $updates + $diagnostics)
All = @(Get-SystemCleanupHandlers)
None = @()
}
}
function Resolve-SystemCleanupDiskCleanupItems {
param($Value)
$items = @($Value | ForEach-Object { ([string]$_).Split(',') } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
if (-not $items.Count) { throw 'CleanupDiskCleanupItems cannot be blank. Select None to disable Disk Cleanup.' }
$presets = Get-SystemCleanupDiskCleanupPresets
if ($items.Count -eq 1) {
foreach ($preset in $presets.Keys) {
if ($items[0] -ieq $preset) {
return [pscustomobject]@{ Preset = $preset; Items = @($presets[$preset]) }
}
}
}
# Exact lists remain supported for existing/manual callers. Presets cannot be
# combined with other presets or handlers; in particular, None must stand alone.
$handlers = @(Get-SystemCleanupHandlers)
$selected = @()
foreach ($item in $items) {
$match = @($handlers | Where-Object { $_ -ieq $item })
if (-not $match.Count) {
throw "Unknown Disk Cleanup preset or item: '$item'. Select one preset ($($presets.Keys -join ', ')) or exact handler names. Do not mix presets with other values."
}
if ($match[0] -notin $selected) { $selected += $match[0] }
}
return [pscustomobject]@{ Preset = 'Custom'; Items = @($selected) }
}
function Get-SystemCleanupOptions {
# Reject stale callers instead of silently re-enabling cleanup when their
# former false flag is ignored and the new Standard default takes effect.
if ($null -ne (Get-Variable -Name CleanupDiskCleanup -ErrorAction SilentlyContinue)) {
throw 'CleanupDiskCleanup has been removed. Remove it from Syncro/the caller and select CleanupDiskCleanupItems=None to disable Disk Cleanup.'
}
$options = @{}
$defaults = Get-SystemCleanupDefaults
foreach ($name in $defaults.Keys) {
$variable = Get-Variable -Name $name -ErrorAction SilentlyContinue
$value = if ($null -eq $variable) { $defaults[$name] } else { $variable.Value }
if ($defaults[$name] -is [bool]) {
# Do not cast RMM text to [bool]: [bool]'false' is true.
switch -Regex ([string]$value) {
'^(?i:\s*(\$?true|yes|1)\s*)$' { $value = $true; break }
'^(?i:\s*(\$?false|no|0)\s*)$' { $value = $false; break }
default { throw "$name must be true or false (received '$value')." }
}
} elseif ($defaults[$name] -is [int]) {
$number = 0
if (-not [int]::TryParse([string]$value, [ref]$number) -or $number -lt 1 -or $number -gt 3650) {
throw "$name must be a whole number from 1 to 3650."
}
$value = $number
} else {
$selection = Resolve-SystemCleanupDiskCleanupItems $value
$options.DiskCleanupPreset = $selection.Preset
$value = @($selection.Items)
}
$options[$name.Substring(7)] = $value
}
return $options
}
function Get-SystemCleanupOS {
$os = @(Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop)
if ($os.Count -ne 1 -or $os[0].ProductType -notin @(1, 2, 3)) {
throw 'Cannot identify OS ProductType; no cleanup will run.'
}
return [pscustomobject]@{ IsServer = ($os[0].ProductType -ne 1); Caption = $os[0].Caption }
}
function Write-SystemCleanupMessage {
param([string]$Message, [switch]$Detail)
# Host/information stream keeps logs out of helper return values, even with Tools loaded.
if ($Detail) { Write-Verbose "[SystemCleanup] $Message" }
else { Write-Host "[SystemCleanup] $Message" }
}
function Test-SystemCleanupPath {
param([string]$Path, [string]$Root)
if ($Path -notmatch '^[A-Za-z]:\\' -or $Root -notmatch '^[A-Za-z]:\\') { return $false }
$full = [IO.Path]::GetFullPath($Path).TrimEnd('\')
$base = [IO.Path]::GetFullPath($Root).TrimEnd('\')
if ($base.Length -le 2 -or ($full -ne $base -and -not $full.StartsWith($base + '\', [StringComparison]::OrdinalIgnoreCase))) { return $false }
# Check every ancestor, not just the leaf. Never follow a junction into another tree.
$probe = $full
while ($probe.Length -gt 3) {
$item = Get-Item -LiteralPath $probe -Force -ErrorAction Stop
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { return $false }
$probe = Split-Path -Parent $probe
}
return $true
}
function Get-SystemCleanupChildren {
param([string]$Root)
if (-not (Test-Path -LiteralPath $Root)) { return }
if (-not (Test-SystemCleanupPath $Root $Root)) {
Write-SystemCleanupMessage "Skipping linked or unsafe path: $Root"
return
}
# 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 {
param([string]$Root, [switch]$Recurse)
$pending = New-Object 'System.Collections.Generic.Stack[string]'
$pending.Push($Root)
while ($pending.Count) {
$directory = $pending.Pop()
foreach ($item in @(Get-SystemCleanupChildren $directory)) {
if ($item.PSIsContainer) { if ($Recurse) { $pending.Push($item.FullName) } }
else { $item }
}
}
}
function Remove-SystemCleanupFile {
param($Context, [string]$Category, [string]$Root, [string]$Path, [datetime]$Cutoff)
if ($Category -ne 'OfficeStaging' -and $Path -match '(?i)(^|[\\/])EmberkomOfficeDeployment([\\/]|$)') { return }
if (-not (Test-SystemCleanupPath $Path $Root)) { return }
$file = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
if ($file.PSIsContainer -or $file.LastWriteTimeUtc -ge $Cutoff) { return }
if ($Context.Options.ReportOnly) {
# Each category is an independent estimate. A disabled category must not
# consume a file before an enabled category can assess the same file.
$candidates = $Context.Candidates[$Category]
if ($candidates.ContainsKey($file.FullName)) { return }
$candidates[$file.FullName] = [long]$file.Length
} elseif (-not $Context.Seen.Add($file.FullName)) { return }
$stat = $Context.Stats[$Category]
$stat.CandidateBytes += $file.Length
$stat.CandidateFiles++
if ($Context.Options.ReportOnly) { return }
try {
# Literal leaf deletion only. In-use files are skipped, never force-unlocked.
Remove-Item -LiteralPath $file.FullName -Force -ErrorAction Stop
$stat.RemovedBytes += $file.Length
$stat.RemovedFiles++
} catch {
$stat.FailedFiles++
Write-SystemCleanupMessage "Skipped '$Path': $($_.Exception.Message)"
}
}
function Clear-SystemCleanupTree {
param($Context, [string]$Category, [string]$Root, [datetime]$Cutoff,
[string[]]$Include = @('*'), [string[]]$Exclude = @(), [switch]$Recurse)
foreach ($file in @(Get-SystemCleanupFiles $Root -Recurse:$Recurse)) {
$match = @($Include | Where-Object { $file.Name -like $_ }).Count -gt 0
if ($match -and @($Exclude | Where-Object { $file.Name -like $_ }).Count -eq 0) {
Remove-SystemCleanupFile $Context $Category $Root $file.FullName $Cutoff
}
}
# Ordinary temp/cache directories are retained. No recursive directory deletes.
}
function Invoke-SystemCleanupCategory {
param($Context, [string]$Name, [scriptblock]$Action)
$enabled = if ($Name -eq 'DiskCleanup') { @($Context.Options.DiskCleanupItems).Count -gt 0 } else { [bool]$Context.Options[$Name] }
if (-not $enabled -and -not $Context.Options.ReportOnly) { return }
$setting = "Cleanup$Name=$($enabled.ToString().ToLowerInvariant())"
$notes = ''
if ($Name -eq 'DiskCleanup') {
$selection = $Context.Options.DiskCleanupPreset
if ($selection -eq 'Custom') { $selection = $Context.Options.DiskCleanupItems -join ', ' }
$setting = "CleanupDiskCleanupItems=$selection"
$notes = if ($enabled) { "Selected handlers: $($Context.Options.DiskCleanupItems -join ', ')." } else { 'No handlers selected; Disk Cleanup will not run.' }
}
$blocked = $Context.OS.IsServer -and $Name -in @('ShadowCopies', 'DisableHibernation', 'CompactSearch',
'DownloadedExecutables', 'DuplicateDownloads', 'OutlookBackups', 'ITunesBackups', 'DiskCleanup')
$native = $Name -in @('DisableHibernation', 'CompactSearch', 'ShadowCopies', 'DeliveryOptimization', 'ComponentStore', 'DiskCleanup')
$Context.Stats[$Name] = [pscustomobject]@{
Category = $Name; Enabled = $enabled
CandidateFiles = $(if ($native -or $blocked) { $null } else { 0 })
CandidateBytes = $(if ($native -or $blocked) { $null } else { [long]0 })
UsageBytes = $null; UsageNote = ''
RemovedFiles = 0; RemovedBytes = [long]0; FailedFiles = 0
Status = $(if ($Context.Options.ReportOnly) { 'Preview' } else { 'Completed' })
EstimateStatus = $(if ($native) { 'Not estimated' } else { 'Estimated' })
Setting = $setting; Notes = $notes
}
if ($blocked) {
$Context.Stats[$Name].Status = 'Blocked on server'
$Context.Stats[$Name].EstimateStatus = 'Not assessed'
Write-SystemCleanupMessage "BLOCKED on server OS: $Name ($setting)" -Detail:$Context.Options.ReportOnly
return
}
if ($Context.Options.ReportOnly) {
if (-not $Context.ContainsKey('Candidates')) { $Context.Candidates = @{} }
$Context.Candidates[$Name] = New-Object 'System.Collections.Generic.Dictionary[string,long]' ([StringComparer]::OrdinalIgnoreCase)
$selection = if ($enabled) { 'enabled for apply' } else { 'disabled; assessment only' }
Write-SystemCleanupMessage "Assessing $Name ($selection)." -Detail
}
try { & $Action } catch {
$Context.Stats[$Name].Status = 'Failed'
$Context.Stats[$Name].EstimateStatus = 'Incomplete'
$Context.Stats[$Name].Notes = $_.Exception.Message
$Context.Errors++
Write-SystemCleanupMessage "$Name failed: $($_.Exception.Message)" -Detail:$Context.Options.ReportOnly
}
if (-not $Context.Options.ReportOnly) {
$s = $Context.Stats[$Name]
if ($native) { Write-SystemCleanupMessage "$Name : $($s.Status); native savings not measured." }
else { Write-SystemCleanupMessage ("{0}: {1} eligible files / {2:N2} MiB; {3} removed / {4:N2} MiB; {5} skipped; {6}" -f $Name, $s.CandidateFiles, ($s.CandidateBytes / 1MB), $s.RemovedFiles, ($s.RemovedBytes / 1MB), $s.FailedFiles, $s.Status) }
}
}
function Set-SystemCleanupSkipped {
param($Context, [string]$Category, [string]$Reason, [string]$Status = 'Skipped')
$Context.Stats[$Category].Status = $Status
$Context.Stats[$Category].EstimateStatus = 'Not assessed'
$Context.Stats[$Category].Notes = $Reason
Write-SystemCleanupMessage $Reason -Detail:$Context.Options.ReportOnly
}
function Get-SystemCleanupReportTotals {
param($Context)
$enabled = New-Object 'System.Collections.Generic.Dictionary[string,long]' ([StringComparer]::OrdinalIgnoreCase)
$disabled = New-Object 'System.Collections.Generic.Dictionary[string,long]' ([StringComparer]::OrdinalIgnoreCase)
foreach ($row in $Context.Stats.Values) {
if ($row.Status -eq 'Blocked on server' -or -not $Context.Candidates.ContainsKey($row.Category)) { continue }
$target = if ($row.Enabled) { $enabled } else { $disabled }
foreach ($entry in $Context.Candidates[$row.Category].GetEnumerator()) { $target[$entry.Key] = $entry.Value }
}
$enabledBytes = [long]0; $additionalBytes = [long]0; $additionalFiles = 0
foreach ($size in $enabled.Values) { $enabledBytes += $size }
foreach ($entry in $disabled.GetEnumerator()) {
if (-not $enabled.ContainsKey($entry.Key)) { $additionalBytes += $entry.Value; $additionalFiles++ }
}
return [pscustomobject]@{
EnabledFiles = $enabled.Count; EnabledBytes = $enabledBytes
AdditionalDisabledFiles = $additionalFiles; AdditionalDisabledBytes = $additionalBytes
}
}
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 {
param($Context)
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')) {
$rows = @($Context.Stats.Values | Where-Object {
if ($group -eq 'Blocked') { $_.Status -eq 'Blocked on server' }
else { $_.Status -ne 'Blocked on server' -and $_.Enabled -eq ($group -eq 'Enabled') }
} | Sort-Object Category)
$heading = switch ($group) {
Enabled { 'ENABLED - would run with current settings' }
Disabled { 'DISABLED - potential only; will not run' }
Blocked { 'BLOCKED ON SERVER - cannot run' }
}
Write-SystemCleanupMessage $heading
if (-not $rows.Count) { Write-SystemCleanupMessage ' None.' }
foreach ($row in $rows) {
$files = '-'; $size = '-'; $notes = @(); $bytes = $null
if ($row.UsageNote) {
$bytes = $row.UsageBytes
$notes += $row.UsageNote
} elseif ($row.EstimateStatus -eq 'Not estimated') { $notes += 'not estimated' }
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)'
}
Write-SystemCleanupMessage ('{0,-25} {1,8} {2,11} {3}' -f $row.Category, $files, $size, $noteText.Trim())
}
}
Write-SystemCleanupMessage 'Totals count each path once; rows may overlap. Unknown/unassessed savings excluded; disk space freed may differ.'
Write-SystemCleanupMessage 'Settings: Cleanup<Category>; DiskCleanup uses CleanupDiskCleanupItems. Full diagnostics: $VerbosePreference="Continue".'
}
function Test-SystemCleanupAppRunning {
param([string[]]$Names)
# Inventory failure aborts the category instead of assuming the app is closed.
return @((Get-Process -ErrorAction Stop) | Where-Object { $_.ProcessName -in $Names }).Count -gt 0
}
function Invoke-SystemCleanupProcess {
param($Context, [string]$FileName, [string]$Arguments)
$nativeDir = if ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess) { 'Sysnative' } else { 'System32' }
$executable = Join-Path $env:SystemRoot "$nativeDir\$FileName"
if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) { throw "Unavailable: $executable" }
Write-SystemCleanupMessage "$FileName $Arguments (native operation; size not estimated)" -Detail:$Context.Options.ReportOnly
if ($Context.Options.ReportOnly) { return }
$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)." }
}
function Remove-SystemCleanupDuplicates {
param($Context, [string]$Root, [datetime]$Cutoff)
$files = @(Get-SystemCleanupFiles $Root)
foreach ($duplicate in $files) {
if ($duplicate.LastWriteTimeUtc -ge $Cutoff -or $duplicate.BaseName -notmatch '^(.*) \([0-9]+\)$') { continue }
$originalName = $Matches[1] + $duplicate.Extension
$original = @($files | Where-Object { $_.Name -ieq $originalName -and $_.Length -eq $duplicate.Length })
if ($original.Count -ne 1) { continue }
if (-not (Test-SystemCleanupPath $duplicate.FullName $Root) -or -not (Test-SystemCleanupPath $original[0].FullName $Root)) { continue }
$originalStream = $null; $duplicateStream = $null
try {
# Hold read handles through deletion, refusing concurrent writers while hashing.
$sharing = [IO.FileShare]::Read -bor [IO.FileShare]::Delete
$originalStream = [IO.File]::Open($original[0].FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, $sharing)
$duplicateStream = [IO.File]::Open($duplicate.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, $sharing)
$hash = Get-FileHash -InputStream $duplicateStream -Algorithm SHA256 -ErrorAction Stop
$other = Get-FileHash -InputStream $originalStream -Algorithm SHA256 -ErrorAction Stop
if ($hash.Hash -eq $other.Hash) { Remove-SystemCleanupFile $Context 'DuplicateDownloads' $Root $duplicate.FullName $Cutoff }
} catch { Write-SystemCleanupMessage "Skipping changing/in-use duplicate '$($duplicate.FullName)': $($_.Exception.Message)" }
finally {
if ($duplicateStream) { $duplicateStream.Dispose() }
if ($originalStream) { $originalStream.Dispose() }
}
}
}
function Remove-SystemCleanupBundle {
param($Context, [string]$Category, [string]$Root, [datetime]$Cutoff)
# Backups and extracted installers are units: keep the entire unit if anything is recent,
# linked or inaccessible. Preflight in-use files before any deletion.
if (-not (Test-SystemCleanupPath $Root $Root)) { return }
$items = New-Object 'System.Collections.Generic.List[object]'
$pending = New-Object 'System.Collections.Generic.Stack[string]'
$pending.Push($Root)
while ($pending.Count) {
$dir = $pending.Pop()
foreach ($item in @(Get-ChildItem -LiteralPath $dir -Force -ErrorAction Stop)) {
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or $item.LastWriteTimeUtc -ge $Cutoff) { return }
$items.Add($item)
if ($item.PSIsContainer) { $pending.Push($item.FullName) }
}
}
if ((Get-Item -LiteralPath $Root -Force).LastWriteTimeUtc -ge $Cutoff) { return }
if (-not $Context.Options.ReportOnly) {
foreach ($file in @($items | Where-Object { -not $_.PSIsContainer })) {
try {
$probe = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
$probe.Dispose()
} catch { Write-SystemCleanupMessage "Retaining in-use bundle: $Root"; return }
}
}
foreach ($file in @($items | Where-Object { -not $_.PSIsContainer })) {
Remove-SystemCleanupFile $Context $Category $Root $file.FullName $Cutoff
}
if (-not $Context.Options.ReportOnly) {
foreach ($dir in @($items | Where-Object PSIsContainer | Sort-Object { $_.FullName.Length } -Descending) + @(Get-Item -LiteralPath $Root -Force)) {
if ((Test-SystemCleanupPath $dir.FullName $Root) -and @(Get-ChildItem -LiteralPath $dir.FullName -Force -ErrorAction Stop).Count -eq 0) {
# Directory.Delete without recursion cannot delete a newly populated directory.
[IO.Directory]::Delete($dir.FullName, $false)
}
}
}
}
function Get-SystemCleanupOfficeStagingRoots {
param([string[]]$Profiles)
@(
(Join-Path ([IO.Path]::GetTempPath()) 'EmberkomOfficeDeployment')
(Join-Path $env:SystemRoot 'Temp\EmberkomOfficeDeployment')
(Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment')
(Join-Path $env:ProgramData 'EmberkomOfficeDeployment')
foreach ($profile in $Profiles) { Join-Path $profile 'AppData\Local\Temp\EmberkomOfficeDeployment' }
) | Sort-Object -Unique
}
function New-SystemCleanupOfficeMutex {
return New-Object Threading.Mutex($false, 'Global\EmberkomOfficeDeployment')
}
function Clear-SystemCleanupOfficeStaging {
param($Context, [string[]]$Roots, [datetime]$Cutoff)
$rootsPresent = @($Roots | Select-Object -Unique | Where-Object { Test-Path -LiteralPath $_ })
if (-not $rootsPresent.Count) { return }
$mutex = New-SystemCleanupOfficeMutex
$acquired = $false; $retained = 0
try {
try { $acquired = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $acquired = $true }
if (-not $acquired) { Set-SystemCleanupSkipped $Context 'OfficeStaging' 'Office deployment is running; staging retained.'; return }
$processes = @(Get-CimInstance Win32_Process -ErrorAction Stop)
if (@($processes | Where-Object { $_.Name -in @('setup.exe', 'odt.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe') }).Count) {
Set-SystemCleanupSkipped $Context 'OfficeStaging' 'An installer is running; staging retained.'; return
}
# Match Install-MicrosoftOffice365's disposable artifact allowlist. Never delete
# options, logs, XML, user helpers, task markers, locks or the workspace itself.
$names = @('ODT', 'odt.exe', 'odt-download-page.html', 'GetHelp', 'GetHelp.zip', 'media-cache.json',
'MicrosoftEdgeWebview2Setup.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe')
foreach ($root in $rootsPresent) {
if (-not (Test-SystemCleanupPath $root $root)) { $retained++; continue }
foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -Force -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' })) {
try {
if (-not (Test-SystemCleanupPath $folder.FullName $root)) { throw 'Linked or unsafe workspace.' }
$markerPath = Join-Path $folder.FullName 'options.json'
if (-not (Test-Path -LiteralPath $markerPath -PathType Leaf)) { throw 'Missing deployment identity.' }
if (-not (Test-SystemCleanupPath $markerPath $root)) { throw 'Linked deployment identity.' }
$marker = Get-Item -LiteralPath $markerPath -Force -ErrorAction Stop
if ($marker.Length -gt 64KB) { throw 'Oversized deployment identity.' }
$options = Get-Content -LiteralPath $markerPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
if ($options.ProductId -notin @('O365BusinessRetail','O365BusinessEEANoTeamsRetail','O365ProPlusRetail','O365ProPlusEEANoTeamsRetail') -or
$options.OfficeArchitecture -notin @('32','64') -or $options.UpdateChannel -notin @('Current','MonthlyEnterprise','SemiAnnual')) { throw 'Unrecognized deployment identity.' }
if ($folder.LastWriteTimeUtc -ge $Cutoff -or $marker.LastWriteTimeUtc -ge $Cutoff) { throw 'Recent deployment.' }
foreach ($process in $processes) {
foreach ($value in @($process.CommandLine, $process.ExecutablePath)) {
if ($value -and $value.IndexOf($folder.FullName, [StringComparison]::OrdinalIgnoreCase) -ge 0) { throw 'Workspace is referenced by a running process.' }
}
}
$items = New-Object 'System.Collections.Generic.List[object]'
$pending = New-Object 'System.Collections.Generic.Stack[string]'
foreach ($name in $names) {
$target = Join-Path $folder.FullName $name
if (Test-Path -LiteralPath $target) { $pending.Push($target) }
}
while ($pending.Count) {
$target = $pending.Pop()
if (-not (Test-SystemCleanupPath $target $folder.FullName)) { throw 'Linked staging artifact.' }
$item = Get-Item -LiteralPath $target -Force -ErrorAction Stop
if ($item.LastWriteTimeUtc -ge $Cutoff) { throw 'Recent staging artifact.' }
$items.Add($item)
if ($item.PSIsContainer) {
foreach ($child in @(Get-ChildItem -LiteralPath $target -Force -ErrorAction Stop)) { $pending.Push($child.FullName) }
} else {
# Probe in preview too; in-use data is not an eligible estimate.
$probe = [IO.File]::Open($item.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
$probe.Dispose()
}
}
foreach ($file in @($items | Where-Object { -not $_.PSIsContainer })) {
Remove-SystemCleanupFile $Context 'OfficeStaging' $folder.FullName $file.FullName $Cutoff
}
if (-not $Context.Options.ReportOnly) {
foreach ($directory in @($items | Where-Object PSIsContainer | Sort-Object { $_.FullName.Length } -Descending)) {
if ((Test-SystemCleanupPath $directory.FullName $folder.FullName) -and @(Get-ChildItem -LiteralPath $directory.FullName -Force -ErrorAction Stop).Count -eq 0) {
[IO.Directory]::Delete($directory.FullName, $false)
}
}
}
} catch {
$retained++
Write-SystemCleanupMessage "Office staging retained at $($folder.FullName): $($_.Exception.Message)" -Detail
}
}
}
if ($retained) { $Context.Stats.OfficeStaging.Notes = "$retained folder(s) retained: recent, active, unrecognized or unsafe; see verbose." }
} finally {
if ($acquired) { $mutex.ReleaseMutex() }
$mutex.Dispose()
}
}
function Get-SystemCleanupRecycleDate {
param([string]$MetadataPath)
if ((Get-Item -LiteralPath $MetadataPath -Force -ErrorAction Stop).Length -gt 1MB) { throw 'Oversized Recycle Bin metadata.' }
$bytes = [IO.File]::ReadAllBytes($MetadataPath)
if ($bytes.Length -lt 24) { throw 'Truncated Recycle Bin metadata.' }
$version = [BitConverter]::ToInt64($bytes, 0)
if ($version -notin @(1, 2)) { throw "Unknown Recycle Bin metadata version: $version" }
if ($version -eq 1 -and $bytes.Length -ne 544) { throw 'Invalid version 1 Recycle Bin metadata length.' }
if ($version -eq 2) {
if ($bytes.Length -lt 28) { throw 'Truncated version 2 Recycle Bin metadata.' }
$characters = [BitConverter]::ToUInt32($bytes, 24)
if ($characters -eq 0 -or (28L + 2L * $characters) -ne $bytes.Length) { throw 'Invalid version 2 Recycle Bin path length.' }
}
return [DateTime]::FromFileTimeUtc([BitConverter]::ToInt64($bytes, 16))
}
function Clear-SystemCleanupRecycleBin {
param($Context, [string]$Root, [datetime]$Cutoff)
foreach ($sid in @(Get-SystemCleanupChildren $Root | Where-Object { $_.PSIsContainer -and $_.Name -match '^S-1-' })) {
foreach ($metadata in @(Get-SystemCleanupFiles $sid.FullName | Where-Object { $_.Name -clike '$I*' })) {
try {
if ((Get-SystemCleanupRecycleDate $metadata.FullName) -ge $Cutoff) { continue }
$payload = Join-Path $sid.FullName ('$R' + $metadata.Name.Substring(2))
if (Test-Path -LiteralPath $payload) {
if (-not (Test-SystemCleanupPath $payload $sid.FullName)) { continue }
$item = Get-Item -LiteralPath $payload -Force -ErrorAction Stop
if ($item.PSIsContainer) {
Remove-SystemCleanupBundle $Context 'RecycleBin' $payload ([datetime]::MaxValue)
} else { Remove-SystemCleanupFile $Context 'RecycleBin' $sid.FullName $payload ([datetime]::MaxValue) }
}
# Keep metadata if the payload could not be fully removed.
if ($Context.Options.ReportOnly -or -not (Test-Path -LiteralPath $payload)) {
Remove-SystemCleanupFile $Context 'RecycleBin' $sid.FullName $metadata.FullName ([datetime]::MaxValue)
}
} catch { Write-SystemCleanupMessage "Skipping recycle item '$($metadata.FullName)': $($_.Exception.Message)" }
}
}
}
function Invoke-SystemCleanupDiskCleanup {
param($Context)
# 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.' }
$selected = @($Context.Options.DiskCleanupItems)
Write-SystemCleanupMessage "Disk Cleanup selection: $($Context.Options.DiskCleanupPreset); selected items: $($selected -join ', '). Windows controls retention for these handlers." -Detail
if ($Context.Options.ReportOnly) {
$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." -Detail
return
}
if (-not $selected.Count) { return }
if (Test-SystemCleanupAppRunning @('cleanmgr')) { throw 'Another Disk Cleanup process is running.' }
$base = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches'
$keys = @(Get-ChildItem -LiteralPath $base -ErrorAction Stop)
# Pick an unused slot across ALL handlers, so a stale unrelated selection cannot run.
$used = @{}
foreach ($key in $keys) {
foreach ($valueName in $key.GetValueNames()) { $used[$valueName] = $true }
}
$slot = 0
foreach ($candidate in 1000..9999) {
if (-not $used.ContainsKey(('StateFlags{0:D4}' -f $candidate))) { $slot = $candidate; break }
}
if (-not $slot) { throw 'No unused Disk Cleanup settings slot is available.' }
$flag = 'StateFlags{0:D4}' -f $slot
$written = New-Object 'System.Collections.Generic.List[string]'
try {
foreach ($key in $keys) {
if ($key.PSChildName -in $selected) {
# Register before writing, so a partially successful write is restored too.
$written.Add($key.PSPath)
New-ItemProperty -LiteralPath $key.PSPath -Name $flag -Value 2 -PropertyType DWord -ErrorAction Stop | Out-Null
}
}
if ($written.Count) { Invoke-SystemCleanupProcess $Context 'cleanmgr.exe' "/sagerun:$slot" }
else { Write-SystemCleanupMessage 'None of the selected Disk Cleanup handlers are installed.' }
} finally {
# Wait for cleanmgr before removing ONLY the temporary settings owned by this run.
foreach ($path in $written) {
try { Remove-ItemProperty -LiteralPath $path -Name $flag -ErrorAction Stop }
catch { Write-SystemCleanupMessage "Could not remove temporary Disk Cleanup setting $path/$flag : $($_.Exception.Message)"; $Context.Errors++ }
}
}
}
function Invoke-SystemCleanupShadows {
param($Context)
if ($Context.OS.IsServer) { throw 'Shadow-copy deletion is blocked on server OSes.' }
$volumes = @(Get-CimInstance -ClassName Win32_Volume -ErrorAction Stop | Where-Object { $_.DriveLetter -eq $env:SystemDrive })
if ($volumes.Count -ne 1) { throw 'Could not uniquely identify the system volume.' }
$shadows = @(Get-CimInstance -ClassName Win32_ShadowCopy -ErrorAction Stop |
Where-Object { $_.VolumeName -eq $volumes[0].DeviceID } | Sort-Object InstallDate -Descending)
# Use exact IDs from the inventory; never loop /Oldest after a failed deletion.
foreach ($shadow in @($shadows | Select-Object -Skip 1)) {
if ($shadow.ID -notmatch '^\{[0-9a-fA-F-]{36}\}$') { throw 'Invalid shadow-copy identifier.' }
Invoke-SystemCleanupProcess $Context 'vssadmin.exe' "delete shadows /Shadow=$($shadow.ID) /Quiet"
}
}
function Invoke-SystemCleanupSearchCompaction {
param($Context)
if ($Context.OS.IsServer) { throw 'Search compaction is blocked on server OSes.' }
$database = Join-Path $env:ProgramData 'Microsoft\Search\Data\Applications\Windows\Windows.edb'
if (-not (Test-Path -LiteralPath $database -PathType Leaf)) { return }
if (-not (Test-SystemCleanupPath $database (Split-Path -Parent $database))) { return }
if ($Context.Options.ReportOnly) {
Write-SystemCleanupMessage "Would compact $database; size savings cannot be estimated." -Detail
return
}
$drive = New-Object IO.DriveInfo ([IO.Path]::GetPathRoot($database))
if ($drive.AvailableFreeSpace -lt ((Get-Item -LiteralPath $database).Length * 1.2)) { throw 'Insufficient free space for a temporary Search database (120% reserve required).' }
$service = Get-Service -Name WSearch -ErrorAction Stop
if ($service.Status -notin @('Running', 'Stopped')) { throw 'Windows Search is transitioning; try again later.' }
$wasRunning = $service.Status -eq 'Running'
try {
# Preserve the original startup configuration, including delayed automatic start.
if ($wasRunning) {
Stop-Service -Name WSearch -ErrorAction Stop
$service.WaitForStatus('Stopped', [timespan]::FromSeconds(30))
}
$temporary = Join-Path (Split-Path -Parent $database) ('SystemCleanup-' + [guid]::NewGuid().ToString('N') + '.edb')
Invoke-SystemCleanupProcess $Context 'esentutl.exe' ('/d "{0}" /t"{1}" /o' -f $database, $temporary)
} finally {
if ($wasRunning) { Start-Service -Name WSearch -ErrorAction Stop }
}
}
function Invoke-SystemCleanup {
param([hashtable]$Options)
$ErrorActionPreference = 'Stop'
$os = Get-SystemCleanupOS
if ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess) {
throw 'Run this script in 64-bit PowerShell to avoid filesystem and registry redirection.'
}
if (-not $Options.ReportOnly) {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal $identity
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Apply mode requires an elevated Administrator or SYSTEM token.' }
}
# One run per machine, including the registry slot allocation and native operations.
$mutex = New-Object Threading.Mutex($false, 'Global\Emberkom.Start-SystemCleanup')
$acquired = $false
try {
try { $acquired = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $acquired = $true }
if (-not $acquired) { throw 'Another Start-SystemCleanup run is already active.' }
$context = @{
Options = $Options; OS = $os; Stats = [ordered]@{}; Errors = 0; Candidates = @{}
Seen = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
}
Write-SystemCleanupMessage "OS: $($os.Caption); server: $($os.IsServer); report only: $($Options.ReportOnly)"
$now = [datetime]::UtcNow
$tempCutoff = $now.AddDays(-$Options.TempDays)
$diagnosticCutoff = $now.AddDays(-$Options.DiagnosticDays)
$backupCutoff = $now.AddDays(-$Options.BackupDays)
# Inventory registered profiles, including custom profile roots; no C:\Users wildcard.
$profiles = @(Get-CimInstance -ClassName Win32_UserProfile -ErrorAction Stop |
Where-Object { -not $_.Special -and $_.LocalPath } | Select-Object -ExpandProperty LocalPath -Unique)
$serviceProfiles = @(
(Join-Path $env:SystemRoot 'System32\config\systemprofile'),
(Join-Path $env:SystemRoot 'ServiceProfiles\LocalService'),
(Join-Path $env:SystemRoot 'ServiceProfiles\NetworkService')
)
if ([Environment]::Is64BitOperatingSystem) { $serviceProfiles += Join-Path $env:SystemRoot 'SysWOW64\config\systemprofile' }
$allProfiles = @($profiles + $serviceProfiles | Select-Object -Unique)
# Generic temp cleaning must not bypass the AutoCAD process check or dump retention.
$tempExclusions = @('*.ac$', '*.sv$', '*.dmp')
Invoke-SystemCleanupCategory $context 'SystemTemp' {
foreach ($relative in @('Temp', 'SystemTemp')) {
Clear-SystemCleanupTree $context 'SystemTemp' (Join-Path $env:SystemRoot $relative) $tempCutoff -Exclude $tempExclusions -Recurse
}
# Includes .evtx, computer-name logs, AppxErrorReport files, and Chocolatey temp.
}
Invoke-SystemCleanupCategory $context 'OfficeStaging' {
Clear-SystemCleanupOfficeStaging $context (Get-SystemCleanupOfficeStagingRoots $allProfiles) $tempCutoff
}
Invoke-SystemCleanupCategory $context 'UserTemp' {
$acadRunning = Test-SystemCleanupAppRunning @('acad')
foreach ($profile in $profiles) {
$root = Join-Path $profile 'AppData\Local\Temp'
Clear-SystemCleanupTree $context 'UserTemp' $root $tempCutoff -Exclude $tempExclusions -Recurse
if (-not $acadRunning) { Clear-SystemCleanupTree $context 'UserTemp' $root $tempCutoff -Include @('*.ac$') -Recurse }
}
}
Invoke-SystemCleanupCategory $context 'ServiceTemp' {
foreach ($profile in $serviceProfiles) {
Clear-SystemCleanupTree $context 'ServiceTemp' (Join-Path $profile 'AppData\Local\Temp') $tempCutoff -Exclude $tempExclusions -Recurse
}
}
Invoke-SystemCleanupCategory $context 'ActiveCBSLog' {
$cbs = Join-Path $env:SystemRoot 'Logs\CBS'
$archives = @(Get-SystemCleanupFiles $cbs | Where-Object { $_.Name -like 'CbsPersist_*.log' -or $_.Name -like 'CbsPersist_*.cab' })
$total = ($archives | Measure-Object Length -Sum).Sum
# 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') {
Clear-SystemCleanupTree $context 'ActiveCBSLog' $cbs $diagnosticCutoff -Include @('CBS.log')
} 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' {
Clear-SystemCleanupTree $context 'CBSArchives' (Join-Path $env:SystemRoot 'Logs\CBS') $diagnosticCutoff -Include @('CbsPersist_*.log', 'CbsPersist_*.cab')
}
Invoke-SystemCleanupCategory $context 'CrashDumps' {
Clear-SystemCleanupTree $context 'CrashDumps' $env:SystemRoot $diagnosticCutoff -Include @('MEMORY.DMP')
foreach ($relative in @('Minidump', 'LiveKernelReports', 'Temp')) {
Clear-SystemCleanupTree $context 'CrashDumps' (Join-Path $env:SystemRoot $relative) $diagnosticCutoff -Include @('*.dmp') -Recurse
}
Clear-SystemCleanupTree $context 'CrashDumps' (Join-Path $env:ProgramData 'Genetec\Dumps') $diagnosticCutoff -Recurse
foreach ($profile in $allProfiles) {
foreach ($relative in @('AppData\Local\CrashDumps', 'AppData\Local\Temp')) {
Clear-SystemCleanupTree $context 'CrashDumps' (Join-Path $profile $relative) $diagnosticCutoff -Include @('*.dmp') -Recurse
}
}
}
Invoke-SystemCleanupCategory $context 'WERArchives' {
Clear-SystemCleanupTree $context 'WERArchives' (Join-Path $env:ProgramData 'Microsoft\Windows\WER\ReportArchive') $diagnosticCutoff -Recurse
foreach ($profile in $allProfiles) {
Clear-SystemCleanupTree $context 'WERArchives' (Join-Path $profile 'AppData\Local\Microsoft\Windows\WER\ReportArchive') $diagnosticCutoff -Recurse
}
}
Invoke-SystemCleanupCategory $context 'AutodeskInstallers' {
if (Test-SystemCleanupAppRunning @('setup', 'msiexec', 'AdskInstall', 'AdODIS')) { Set-SystemCleanupSkipped $context 'AutodeskInstallers' 'An installer is running; extracted Autodesk payloads retained.'; return }
foreach ($dir in @(Get-SystemCleanupChildren (Join-Path $env:SystemDrive 'Autodesk') | Where-Object { $_.PSIsContainer -and $_.Name -ne 'WI' })) {
Remove-SystemCleanupBundle $context 'AutodeskInstallers' $dir.FullName $tempCutoff
}
}
Invoke-SystemCleanupCategory $context 'RecycleBin' {
Clear-SystemCleanupRecycleBin $context (Join-Path $env:SystemDrive '$Recycle.Bin') $backupCutoff
}
Invoke-SystemCleanupCategory $context 'DownloadedExecutables' {
foreach ($profile in $profiles) { Clear-SystemCleanupTree $context 'DownloadedExecutables' (Join-Path $profile 'Downloads') $backupCutoff -Include @('*.exe') }
}
Invoke-SystemCleanupCategory $context 'DuplicateDownloads' {
foreach ($profile in $profiles) { Remove-SystemCleanupDuplicates $context (Join-Path $profile 'Downloads') $backupCutoff }
}
Invoke-SystemCleanupCategory $context 'OutlookBackups' {
if (Test-SystemCleanupAppRunning @('OUTLOOK')) { Set-SystemCleanupSkipped $context 'OutlookBackups' 'Outlook is running; backups retained.'; return }
foreach ($profile in $profiles) { Clear-SystemCleanupTree $context 'OutlookBackups' (Join-Path $profile 'AppData\Local\Microsoft\Outlook') $backupCutoff -Include @('*.bak') }
}
Invoke-SystemCleanupCategory $context 'ITunesBackups' {
if (Test-SystemCleanupAppRunning @('iTunes', 'AppleDevices')) { Set-SystemCleanupSkipped $context 'ITunesBackups' 'An Apple device application is running; backups retained.'; return }
foreach ($profile in $profiles) {
foreach ($relative in @('AppData\Roaming\Apple Computer\MobileSync\Backup', 'Apple\MobileSync\Backup')) {
foreach ($dir in @(Get-SystemCleanupChildren (Join-Path $profile $relative) | Where-Object PSIsContainer)) {
Remove-SystemCleanupBundle $context 'ITunesBackups' $dir.FullName $backupCutoff
}
}
}
}
Invoke-SystemCleanupCategory $context 'AppleDownloads' {
if (Test-SystemCleanupAppRunning @('iTunes', 'AppleDevices')) { Set-SystemCleanupSkipped $context 'AppleDownloads' 'An Apple device application is running; downloads retained.'; return }
foreach ($profile in $profiles) {
foreach ($device in @('iPhone', 'iPad', 'iPod')) {
Clear-SystemCleanupTree $context 'AppleDownloads' (Join-Path $profile "AppData\Roaming\Apple Computer\iTunes\$device Software Updates") $tempCutoff -Include @('*.ipsw')
}
Clear-SystemCleanupTree $context 'AppleDownloads' (Join-Path $profile 'Music\iTunes\iTunes Media\Mobile Applications') $tempCutoff -Include @('*.ipa')
}
}
Invoke-SystemCleanupCategory $context 'BrowserCache' {
foreach ($browser in @(@{Name='chrome'; Root='Google\Chrome\User Data'}, @{Name='msedge'; Root='Microsoft\Edge\User Data'})) {
if (Test-SystemCleanupAppRunning @($browser.Name)) {
$context.Stats.BrowserCache.Status = 'Partial'
$context.Stats.BrowserCache.EstimateStatus = 'Incomplete'
$context.Stats.BrowserCache.Notes += "$($browser.Name) is running; its cache was not assessed. "
Write-SystemCleanupMessage "$($browser.Name) is running; its caches retained." -Detail:$Options.ReportOnly
continue
}
foreach ($profile in $profiles) {
foreach ($browserProfile in @(Get-SystemCleanupChildren (Join-Path $profile ('AppData\Local\' + $browser.Root)) | Where-Object { $_.PSIsContainer -and ($_.Name -eq 'Default' -or $_.Name -match '^Profile \d+$') })) {
foreach ($cache in @('Cache', 'Code Cache', 'GPUCache')) {
Clear-SystemCleanupTree $context 'BrowserCache' (Join-Path $browserProfile.FullName $cache) $tempCutoff -Recurse
}
}
}
}
}
Invoke-SystemCleanupCategory $context 'RevitJournals' {
if (Test-SystemCleanupAppRunning @('Revit')) { Set-SystemCleanupSkipped $context 'RevitJournals' 'Revit is running; journals retained.'; return }
foreach ($profile in $profiles) {
foreach ($version in @(Get-SystemCleanupChildren (Join-Path $profile 'AppData\Local\Autodesk\Revit') | Where-Object { $_.PSIsContainer -and $_.Name -like 'Autodesk Revit *' })) {
Clear-SystemCleanupTree $context 'RevitJournals' (Join-Path $version.FullName 'Journals') $diagnosticCutoff -Include @('journal*.txt')
}
}
}
Invoke-SystemCleanupCategory $context 'DisableHibernation' {
if (Test-Path -LiteralPath (Join-Path $env:SystemDrive 'hiberfil.sys')) { Invoke-SystemCleanupProcess $context 'powercfg.exe' '/hibernate off' }
}
Invoke-SystemCleanupCategory $context 'CompactSearch' { Invoke-SystemCleanupSearchCompaction $context }
Invoke-SystemCleanupCategory $context 'ShadowCopies' { Invoke-SystemCleanupShadows $context }
Invoke-SystemCleanupCategory $context 'DeliveryOptimization' {
if (-not (Get-Command Delete-DeliveryOptimizationCache -ErrorAction SilentlyContinue)) {
if ($Options.ReportOnly) { Set-SystemCleanupSkipped $context 'DeliveryOptimization' 'Delivery Optimization cmdlet is not installed.' -Status 'Unavailable'; return }
throw 'Delivery Optimization cmdlet is not installed.'
}
Write-SystemCleanupMessage 'Delivery Optimization: unpinned cache only; size not estimated.' -Detail:$Options.ReportOnly
if (-not $Options.ReportOnly) { Delete-DeliveryOptimizationCache -Force -ErrorAction Stop }
}
Invoke-SystemCleanupCategory $context 'ComponentStore' {
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.' -Detail:$Options.ReportOnly
}
Invoke-SystemCleanupCategory $context 'DiskCleanup' { Invoke-SystemCleanupDiskCleanup $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." }
return @($context.Stats.Values | Sort-Object @{Expression={ if ($_.Status -eq 'Blocked on server') { 2 } elseif ($_.Enabled) { 0 } else { 1 } }}, Category)
} finally {
if ($acquired) { $mutex.ReleaseMutex() }
$mutex.Dispose()
}
}
# Read inherited caller variables before entering the implementation's local scope.
# 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
Function IsURLValid {
param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$URL)
@@ -853,6 +885,87 @@ Function Disable-Log {
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 Import-MSP360Module {
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.
+61 -23
View File
@@ -6,7 +6,7 @@ The selection identifies the client's purchased subscription; it does not discov
## 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.
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.
@@ -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.
`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.
@@ -60,17 +60,21 @@ Business Basic, E1, frontline/web-only plans, education/government variants, con
## Download, removal, and installation
With `ValidateBeforeChanges=true`, the script checks the subscription/activation combination, host and OS prerequisites, running apps, and availability of registered user profiles. It downloads and verifies ODT, the user cleanup helper, the full Office payload, and the selected companion bootstrappers. It writes the installation/removal XML and options, and returns `ValidationPassed` with `OfficeRemovalMethod=SilentODT`, the selected product, version, company, Teams choice, existing Office inventory, and running apps. It does **not** close apps, uninstall, clear identity/credentials, load user hives, register per-user cleanup tasks, or install apps. `OfficeAppShutdown=Force` only reports running apps in this mode; `Abort` fails validation if any are running.
With `ValidateBeforeChanges=true`, the script checks the subscription/activation combination, host and OS prerequisites, running apps, registered profile availability, 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.
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.
**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.
@@ -93,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.
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.
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:
@@ -112,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`.
## 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
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.
@@ -124,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.
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.
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
- A completed staging pass records a protected `media-cache.json` inventory with file sizes, version, original creation time, and matching product, architecture, channel, language, Windows 10 target (when applicable), and companion download definitions. Compatible runs move these installers into their new workspace instead of copying or redownloading them. This keeps each deployment's user cleanup ID separate. Company, activation, shutdown, and reboot selections are applied to freshly generated XML. The receipt reports `CachedMediaReused`. The new cache format refreshes caches created by older script versions once; subsequent matching validation/deployment runs reuse them normally.
- Downloads live under `EmberkomOfficeDeployment\<deployment-id>` in `[IO.Path]::GetTempPath()` for the execution account. In Syncro this is SYSTEM's temp location, not the signed-in user's temp directory. The actual path is reported in `Workspace`. Folder permissions prevent standard users from changing executable content.
- Cached installers remain eligible for reuse for **seven days**, provided the files still exist. This is a freshness limit, not a scheduled deletion policy. Expired, incomplete, unsigned, or incompatible caches are not reused. Size checks detect truncation, not same-size payload changes; the script leaves payload integrity checking to Microsoft's installer. Changing to a no-Teams plan cannot reuse a Teams-enabled cache. A failed deployment or a stop for restart leaves media in temp for a retry. Repeated validation does not extend the original freshness limit. If routine temp cleanup purges it first, the next run downloads fresh media.
- Once Office and all selected companion apps are verified installed, the same script run deletes its entire temporary workspace, including the Office payload, ODT package/extraction, companion bootstrappers, cache manifest, helper copy, generated XML, and temporary process logs. It also removes unused older temporary deployment workspaces and known installer downloads from older ProgramData stages. Deferred-user files in ProgramData, installed applications, and Microsoft's servicing caches are preserved.
- There is **no daily housekeeping task, resident housekeeping script, or separate log-retention job**. Validation/failure leftovers are subject to the endpoint's existing temp-cleanup routines; exact deletion timing depends on those routines. File removal rejects junctions/symlinks and skips workspaces referenced by running processes.
- Cleanup failures do not change a verified installation into an installation failure. `ArtifactCleanupPending=true` and a console warning identify files left behind; there is no scheduled retry. A later successful deployment or the endpoint's ordinary temp cleanup can remove them.
Earlier ProgramData caches are not searched for reuse in the new temp location. Their known installer files are still cleaned after a successful deployment, while existing user helpers and diagnostic files are preserved. An RMM hard termination can interrupt cleanup; leftovers remain in temp rather than depending on a new background process.
- Each actual installation uses a fresh protected `EmberkomOfficeDeployment\<deployment-id>` directory in the execution account's `[IO.Path]::GetTempPath()`. Under SYSTEM this can be `C:\Windows\SystemTemp`. There is no cross-run reuse of media, manifests, options or XML.
- 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.
- `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`.
- 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.
- 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.
- 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.
## Results and troubleshooting
@@ -147,16 +179,20 @@ 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. |
| `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. |
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.
ODT's redirected `stdout`/`stderr` files can be empty even when installation fails. Microsoft writes native setup/Click-to-Run logs in the execution account's temp directory and `C:\Windows\Temp`; SYSTEM's temp may be `C:\Windows\SystemTemp`. On an ODT failure, the script searches those folders for recent, nonempty Office/setup or computer-name logs and appends bounded error excerpts and their full paths to the existing Tools diagnostic log. Look for `Native Office log:` and `Native Office detail:`. Collection is read-only, creates no task or additional resident helper, and cannot override the original installer exit code. Excerpts are clues; retain the full native logs when diagnosing a failure.
Exit `17004` is documented as `ERROR_COMPLETING_SCENARIO_NEED_CLEAN_UP`, with possible reasons including unknown SKUs or unavailable CDN content. It does not establish that an old Office installation needs a scrub. Inspect the native error details before changing removal behavior or repeating a destructive deployment. See [Microsoft's Office CSP error table](https://learn.microsoft.com/en-us/windows/client-management/mdm/office-csp) and [ODT troubleshooting log locations](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/deploy-microsoft-365-apps-local-source).
If machine companion removal still fails verification, the error identifies the remaining component, version, and registry location, along with the uninstall log folder. The main log also records which add-in registrations were left to user cleanup. An uninstall exit code of `1605` alone does not establish that all users' installations are gone; Windows Installer context determines which stage handles the add-in. This failure occurs before Office removal, identity reset, and reinstallation, but companion apps may already have been removed.
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.
@@ -164,10 +200,12 @@ The installer verifies the selected Office product, bitness, and downloaded vers
## Verification
Run `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\Install-MicrosoftOffice365.Tests.ps1` for offline checks. They require Windows PowerShell 5.1 and exercise the default validation gate (including `Force`), explicit deployment opt-out, log/console routing with the real Tools helpers, XML, removal-result handling, bounded cache deletion, companion installer failures/verification, deferred cleanup protection, and the unchanged `Run-Script` receiving injected strings through the shim with a mocked workload. Recovery checks simulate busy MSI, delayed registration, transient downloads, Appx removal races, persistent failures, and completed-task housekeeping errors. ODT removal tests cover silent XML, absent Office, mixed MSI/Click-to-Run installations, leftovers, read errors, MSI verification after installation, restart results, and absence of an interactive fallback. An inert executable checks actual native argument passing; a 32-bit Windows PowerShell child checks relaunch into 64-bit Windows PowerShell 5.1 and exit-code propagation. Tests use a separate mutex and do not run Microsoft installers or clear actual credentials.
Run `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\Install-MicrosoftOffice365.Tests.ps1` for offline checks 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.
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.
## Maintaining deployment definitions
+299
View File
@@ -0,0 +1,299 @@
# System cleanup
`Start-SystemCleanup.ps1` combines the operations of `Cleanup-SystemTempFiles.ps1`
and `Start-Cleanup.ps1`, with additional cache and diagnostic targets. The old
scripts remain unchanged. Upload `rmm/Start-SystemCleanup.ps1` to the RMM and run
as SYSTEM under **64-bit Windows PowerShell 5.1**. No reboot is initiated.
On 64-bit Windows the core rejects a 32-bit host before changes.
## First run and configuration
Define the script variables in Syncro using the names below **without `$`**.
Use Dropdown variables with `true` and `false` choices for boolean options, and
a single-selection Dropdown for `CleanupDiskCleanupItems` with the five presets
below. Select `Standard` for the usual Disk Cleanup behavior. The three day counts
can be Runtime variables, requiring a nonempty number each run; omit those variable
definitions if you want the core's defaults instead. Syncro supplies all values as
strings. Uploading the shim does not create these variable definitions in Syncro.
Remove the former `CleanupDiskCleanup` variable from Syncro and any manual callers.
`CleanupDiskCleanupItems=None` is now the only operator setting to disable native
Disk Cleanup. A caller still supplying the removed boolean fails before cleanup,
with migration instructions, so an old `false` value cannot be silently ignored.
Like `rmm/Install-MicrosoftOffice365.ps1`, the shim documents the variables but
does not assign them. It loads Tools.ps1 and calls
`Run-Script -LivePSScript Start-SystemCleanup`, preserving Syncro's injected
variables through the dot-sourced caller scope; do not add `-Arguments`. The core
parses these strings and supplies defaults for absent variables, including direct
use. The core does not need to download Tools.ps1 itself.
Run once with `CleanupReportOnly=true`, then set it to `false` to apply. Report
mode assesses **all categories regardless of their enablement**, using the current
retention settings. It leaves the enablement variables unchanged. The compact
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.
- **Disabled:** potential savings only; these categories will not run during apply
unless you enable their corresponding `Cleanup*` variables.
- **Blocked on server:** listed for visibility, without scanning or executing their
actions. These cannot be enabled on a server.
For example, `CleanupDownloadedExecutables=false` still reports old downloaded
executables in the Disabled section on a client. With `CleanupReportOnly=false`,
that category is skipped entirely until explicitly enabled.
File categories report their independent eligible file counts and logical bytes.
These category estimates can overlap (for example, a duplicate downloaded EXE).
The enabled total counts each file path once. The disabled total shows additional
unique file bytes beyond those already counted in enabled categories. Native
operations such as Disk Cleanup, Search compaction, Delivery Optimization,
and component cleanup show `-` and **not estimated**, not
zero. Disk Cleanup shows its preset (or Custom) and selected handler count.
`None` places Disk Cleanup in the Disabled section. Servers always place it in
the Blocked section, regardless of the preset.
Skipped/unavailable categories say **not assessed**; failed or partially assessed
categories are labeled incomplete. In-use application checks remain enforced, so
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.
The report-only diagnostics run regardless of the corresponding cleanup flags:
- **DisableHibernation:** the category's MiB column shows the current system-drive
`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
or unrecognized boolean values fail before cleanup. Retention values must be
whole days from 1 through 3650. Unknown Disk Cleanup presets/handler names, blank
selections, and mixtures of presets with other values also fail before cleanup.
| Variable | Default | Purpose |
| --- | --- | --- |
| `CleanupReportOnly` | true | Assess all categories versus apply enabled categories only |
| `CleanupTempDays` | 7 | Temp files, installers, abandoned Office staging, browser cache, Apple downloads |
| `CleanupDiagnosticDays` | 30 | CBS, WER archives, dumps, Revit journals |
| `CleanupBackupDays` | 30 | Downloads, backups, time spent in Recycle Bin |
| `CleanupSystemTemp` | true | Windows Temp and SystemTemp, including EVTX, misc logs, AppxErrorReport, Chocolatey; excludes Office staging |
| `CleanupOfficeStaging` | true | Recognized abandoned Office deployment media, using CleanupTempDays; preserves diagnostics and deferred-user helpers |
| `CleanupUserTemp` | true | Registered user profiles' Local Temp; AutoCAD `.ac$` only with AutoCAD closed |
| `CleanupServiceTemp` | true | LocalService, NetworkService, SYSTEM profile temp folders |
| `CleanupCBSArchives` | true | `CbsPersist_*.log` and `CbsPersist_*.cab` |
| `CleanupActiveCBSLog` | false | Old CBS.log, only with TrustedInstaller already stopped and archives >=200 MiB |
| `CleanupCrashDumps` | true | MEMORY.DMP, Minidump, LiveKernelReports including PDCRevocation, Genetec Dumps, user/service CrashDumps and temp `.dmp` |
| `CleanupWERArchives` | true | System/user/service WER ReportArchive; queues retained |
| `CleanupAutodeskInstallers` | false | Old extracted directories under system drive Autodesk, excluding WI |
| `CleanupRecycleBin` | false | System-drive recycle items, using deletion date from `$I` metadata |
| `CleanupDisableHibernation` | false | `powercfg /hibernate off` |
| `CleanupCompactSearch` | false | Compact Windows.edb with esentutl; temporarily stop WSearch |
| `CleanupShadowCopies` | false | Delete all but newest system-volume shadow copy |
| `CleanupDownloadedExecutables` | false | Old `.exe` files in each profile's Downloads |
| `CleanupDuplicateDownloads` | false | Old `name (number).ext` files with a matching original and SHA-256 |
| `CleanupOutlookBackups` | false | Old Outlook `.bak` files, with Outlook closed |
| `CleanupITunesBackups` | false | Old complete MobileSync backup directories, with Apple apps closed |
| `CleanupAppleDownloads` | false | Old IPSW/IPA files from the previously commented-out iTunes block |
| `CleanupBrowserCache` | false | Chrome/Edge Cache, Code Cache, GPUCache in Default/Profile N, with that browser closed |
| `CleanupRevitJournals` | true | Old journal*.txt only, with Revit closed |
| `CleanupDeliveryOptimization` | false | Supported cache cmdlet, retaining pinned content |
| `CleanupComponentStore` | false | Request Windows StartComponentCleanup scheduled task; asynchronous |
| `CleanupDiskCleanupItems` | Standard | Disk Cleanup preset; None disables it; clients only. Exact handler lists/arrays also accepted |
## Disk Cleanup presets
Configure these exact dropdown choices for `CleanupDiskCleanupItems`:
| Preset | Selected handlers |
| --- | --- |
| `Standard` (default) | Downloaded Program Files; Internet Cache Files; Thumbnail Cache; Active Setup Temp Folders; Temporary Setup Files; Windows Defender; RetailDemo Offline Content |
| `StandardAndUpdates` | All Standard handlers, plus Service Pack Cleanup; Update Cleanup; Upgrade Discarded Files; Windows Upgrade Log Files |
| `StandardUpdatesAndDiagnostics` | All StandardAndUpdates handlers, plus Memory Dump Files; Old ChkDsk Files; System error memory dump files; System error minidump files; Setup Log Files; Windows Error Reporting Archive Files; Windows Error Reporting Queue Files; Windows Error Reporting System Archive Files; Windows Error Reporting System Queue Files; Windows Error Reporting Temp Files |
| `All` | All 35 supported legacy handlers listed below, including Recycle Bin, user file versions, previous installations, and Windows ESD installation files |
| `None` | No handlers; native Disk Cleanup does not run |
Presets are cumulative and case-insensitive; surrounding whitespace is ignored.
`Standard` preserves the previous default selection. `All` selects the explicit
supported list, not arbitrary additional handlers installed on an endpoint.
No preset changes other `Cleanup*` flags or bypasses the server exclusion.
Exact comma-separated handler names and arrays remain supported for manual or
existing callers, for example `Thumbnail Cache,Internet Cache Files`. They are
reported as a custom selection. Use one preset or a list of exact handlers; do
not mix them. A supplied blank/null value is invalid; an absent variable defaults
to `Standard`. Use the nonempty value `None` to disable native Disk Cleanup.
## Server policy
`Win32_OperatingSystem.ProductType` identifies clients (1), domain controllers
(2), and other servers (3). Both server types are blocked from these categories,
even if enabled or selected by a Disk Cleanup preset:
- ShadowCopies
- DisableHibernation
- CompactSearch
- DownloadedExecutables and DuplicateDownloads
- OutlookBackups and ITunesBackups
- DiskCleanup (every handler, including any newly selected items)
Unknown or failed OS identification stops the run before changes. There is no
override. Disk Cleanup availability varies by Server version/installation; the
OS gate is enforced even if cleanmgr.exe exists. Native and file categories
outside this list can run on both clients and servers when enabled.
## All legacy Disk Cleanup operations
Every handler from Start-Cleanup.ps1 remains selectable, including those that
were disabled there. The old groups are listed here for migration; select a
preset above or exact handler names in `CleanupDiskCleanupItems`. The old group
names themselves are not accepted as presets.
| Old group | Handler names |
| --- | --- |
| User | Downloaded Program Files; Internet Cache Files; Offline Pages Files; Recycle Bin; Temporary Files; Thumbnail Cache; User file versions |
| System | Active Setup Temp Folders; BranchCache; Memory Dump Files; Old ChkDsk Files; RetailDemo Offline Content; Temporary Files; System error memory dump files; System error minidump files; Temporary Setup Files; Windows Defender; Windows Error Reporting Archive Files; Windows Error Reporting Queue Files; Windows Error Reporting System Archive Files; Windows Error Reporting System Queue Files; Windows Error Reporting Temp Files |
| WindowsUpdate | Service Pack Cleanup; Update Cleanup; Upgrade Discarded Files; Windows Upgrade Log Files |
| WindowsPreviousVersions | Previous Installations; Setup Log Files |
| Invasive | Windows ESD installation files |
| Misc | Content Indexer Cleaner; Delivery Optimization Files; Device Driver Packages; GameNewsFiles; GameStatisticsFiles; GameUpdateFiles; Temporary Sync Files |
Selecting a handler explicitly permits Windows to apply that handler's own
retention rules. The script's day settings **do not apply to cleanmgr**. For
example, its Recycle Bin/dump/WER handlers can remove recent data; its previous
installation/service pack/ESD handlers can remove rollback or recovery options.
`/sagerun` enumerates drives; it is not restricted to the system drive. The
default selection omits those recovery and diagnostic handlers.
Instead of persistent sageset flags or legacy NoSettings/NoCleaning/DeleteSettings
modes, each live run allocates an unused settings slot across all registered
handlers, writes only selected handlers, waits for cleanmgr, then removes its own
temporary flags in finally. Existing settings are preserved. Abnormal process
termination can leave a temporary slot behind; future runs skip occupied slots.
## Deletion and operational boundaries
- `OfficeStaging` checks the execution account's temp directory, Windows Temp and
SystemTemp, registered user/service profile temp directories, and legacy
ProgramData, under `EmberkomOfficeDeployment`. It runs on clients and servers.
The deployment mutex must be available, process inventory must succeed, and no
recognized installer may be running. Each workspace must have a GUID name and a
bounded, recognizable `options.json`; its directory, identity and every payload
artifact must be older than `CleanupTempDays`. Recent, linked, locked, unrecognized
or process-referenced workspaces are retained, including in report-only estimates.
- Office cleanup deletes only named payload artifacts (ODT, companion installers,
old GetHelp downloads and cache manifests). It preserves logs, options, XML,
helper scripts, locks, task markers, unknown files and the workspace itself.
Generic temp scans exclude this subtree, so they cannot bypass the dedicated
option, retention or active-deployment checks. Report-only lists eligible media
even when `CleanupOfficeStaging=false`; apply skips that disabled category.
Process and mutex skips remain visible in the compact report; per-folder
retention reasons are available through verbose output.
- Inspect each file's modification time; an old parent never authorizes deletion
of newer children. Ordinary cache/temp directories are retained.
- Use literal local paths, verify containment, and skip reparse points and linked
ancestors (including OneDrive placeholders). UNC paths and redirected profile
folders reached through links are skipped. No ownership or ACL changes.
- Skip in-use files. A category inventory failure is reported and later categories
continue; the run fails at the end if a category/maintenance operation failed.
- Generic temp cleanup excludes `.dmp`, `.ac$`, and AutoCAD `.sv$` autosaves.
Dumps get diagnostic retention; `.ac$` gets a separate closed-app check;
`.sv$` is retained. Revit model/recovery files and browser site storage are
outside the dedicated cache/journal targets.
- Backup/installer directories are inspected as complete units. Recent content
or links retain the unit, and apply mode probes for in-use files before deleting
any part of a unit. No recursive Remove-Item is used. Failed file deletion
retains the remaining directory; there is no transaction or rollback.
- Recycle Bin cleanup uses `$I` FILETIME metadata and removes the paired `$R`
content before its metadata. Unsupported/corrupt metadata is retained.
- Downloads are not discovered via redirected Known Folders. Duplicate matching
requires extension, size, and SHA-256 equality. Read handles prevent concurrent
writes during hashing/deletion; filesystem activity outside the script can still
rename or delete files, so this remains an opt-in operation.
- Active CBS cleanup never stops TrustedInstaller. Search compaction preserves
service startup settings, requires free space for a temporary database, and
restarts WSearch in finally only if it was originally running. An interrupted
native compaction can leave its uniquely named temporary database for inspection.
- VSS deletion uses exact inventoried snapshot IDs and preserves the newest;
native failures stop that category. Backup-managed snapshots may refuse deletion.
- Component cleanup uses Windows' scheduled task, with no ResetBase or direct
WinSxS deletion. Task submission is reported separately from completion.
- Native operations report exit codes and use hidden windows. No hard execution
timeout is imposed; allow adequate RMM runtime if enabling maintenance work.
- Byte counters are file lengths, not guaranteed physical disk savings (compression,
sparse files, hard links, and native cleanup affect actual reclaimed space).
## Validation
Run `powershell.exe -NoProfile -File tests/Start-SystemCleanup.Tests.ps1`.
Tests load function definitions via the AST, use disposable fixture directories,
and mock OS, registry, native processes, and service operations. They do not run
cleanup against the host's Windows folders or invoke maintenance programs.
Coverage includes disabled-category estimates, separate report groups, unique
totals for overlapping categories, and disabled categories remaining untouched in
apply mode. Preset tests verify exact handler membership, cumulative selections,
RMM scope preservation, None disabling native work, and the server exclusions.
Output tests cover the duplicate-object regression, a 23-category preview under
4 KiB including diagnostics, separate enabled/disabled sections, and preservation
of diagnostic notes. Regression checks ensure DISM analysis is absent and report
diagnostics launch no native programs.
Hibernation/VSS tests cover usage in category MiB columns, zero for absence,
unknown sizes after access failures, cross-drive storage, server exclusions, no
duplicate diagnostic lines, and usage staying out of savings totals.
Office staging tests cover Windows SystemTemp and legacy ProgramData, complete
artifact selection, identity/age/link/lock/process guards, deployment mutex
contention, disabled categories, server support, generic-temp exclusion, and
preservation of diagnostics and deferred-user files.
References: [OS ProductType](https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-operatingsystem),
[Disk Cleanup](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cleanmgr),
[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).
+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
# EmberkomOfficeUserCleanup-v4
# Run only as the affected user, at limited privilege; staged by the Office installer.
# EmberkomOfficeUserCleanup-v5
# 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)
function Get-OfficeUserCleanupDefinitions {
@@ -184,7 +184,9 @@ $null = Start-Transcript -Path (Join-Path $logFolder "$DeploymentId.log") -Appen
try {
$null = New-Item -Path $marker -Force
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'
} catch {
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')))
# Set the edition of the ECB agent.
@@ -9,4 +10,4 @@ $MSP360Username = '{[MSP360_Username]}'
$MSP360Password = '{[MSP360_Password]}'
# 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.
# Configure these [string] Dropdown variables in Syncro:
# [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]$OfficeArchitecture - Auto (default), 64, 32
# [string]$UpdateChannel - Current (default), MonthlyEnterprise, SemiAnnual
+59
View File
@@ -0,0 +1,59 @@
#Requires -Version 5.1
# Configure these [string] Dropdown variables in Syncro, each with true/false choices:
# [string]$CleanupReportOnly - true (default: assess all), false (apply enabled only)
# [string]$CleanupSystemTemp - true (default), false
# [string]$CleanupOfficeStaging - true (default), false; uses CleanupTempDays
# [string]$CleanupUserTemp - true (default), false
# [string]$CleanupServiceTemp - true (default), false
# [string]$CleanupCBSArchives - true (default), false
# [string]$CleanupActiveCBSLog - false (default), true
# [string]$CleanupCrashDumps - true (default), false
# [string]$CleanupWERArchives - true (default), false
# [string]$CleanupAutodeskInstallers - false (default), true
# [string]$CleanupRecycleBin - false (default), true
# [string]$CleanupDisableHibernation - false (default), true
# [string]$CleanupCompactSearch - false (default), true
# [string]$CleanupShadowCopies - false (default), true
# [string]$CleanupDownloadedExecutables - false (default), true
# [string]$CleanupDuplicateDownloads - false (default), true
# [string]$CleanupOutlookBackups - false (default), true
# [string]$CleanupITunesBackups - false (default), true
# [string]$CleanupAppleDownloads - false (default), true
# [string]$CleanupBrowserCache - false (default), true
# [string]$CleanupRevitJournals - true (default), false
# [string]$CleanupDeliveryOptimization - false (default), true
# [string]$CleanupComponentStore - false (default), true
# Configure this [string] Dropdown variable in Syncro with these exact choices:
# [string]$CleanupDiskCleanupItems - Standard (default)
# StandardAndUpdates
# StandardUpdatesAndDiagnostics
# All
# None
# None disables native Disk Cleanup. All includes Recycle Bin and recovery data.
# Configure these [string] Runtime variables if you need custom retention values:
# [string]$CleanupTempDays - 7 (default); whole days, 1-3650
# [string]$CleanupDiagnosticDays - 30 (default); whole days, 1-3650
# [string]$CleanupBackupDays - 30 (default); whole days, 1-3650
# Runtime values must be entered each run; omit these variables to use core defaults.
# Uploading this file does not define the variables or their selections in Syncro.
# Syncro injects the variables into the caller scope. Do not assign over them here.
# The main script parses the injected strings and supplies defaults for absent variables.
# Every variable configured in Syncro needs a nonempty value.
# 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 exclusions cannot be overridden by these variables. No reboot is initiated.
# OfficeStaging checks Windows Temp/SystemTemp, execution/profile temp and legacy ProgramData.
# Only recognized, aged installer media is eligible; active deployments and user helpers are protected.
$ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
. $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1')))
# No -Arguments: Run-Script must dot-source the core into this caller's scope.
Run-Script -LivePSScript Start-SystemCleanup
+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
}
+606 -112
View File
@@ -37,7 +37,38 @@ try {
# Exercise the real bounded retry loops without delaying offline tests.
function Start-Sleep { param([int]$Seconds) $script:testSleeps += $Seconds }
function Get-FileHash { throw 'Office deployment must not scan file checksums.' }
$diskSpaceCheck = ${function:Assert-OfficeDiskSpace}
# Staging/orchestration fixtures must not depend on this test computer's free space.
function Assert-OfficeDiskSpace { param($Workspace,[switch]$DownloadingMedia) }
$script:testSleeps = @()
& {
function Get-CimInstance {
param($ClassName,$Filter)
Assert-OfficeTest ($ClassName -eq 'Win32_LogicalDisk') 'Disk checks must use read-only logical-disk inventory.'
$script:diskQueries += $Filter
if ($script:diskReadFails) { throw 'Synthetic disk inventory failure' }
if ($Filter -match "DeviceID='([^']+)'") { [pscustomobject]@{FreeSpace=$script:freeBytes[$Matches[1]]} }
}
$script:diskReadFails=$false; $script:diskQueries=@()
$script:freeBytes=@{'C:'=16GB; 'D:'=6GB; 'E:'=10GB}
$output = @(& $diskSpaceCheck -Workspace 'C:\Temp\Office' -InstallPaths @('C:\Windows','C:\Program Files') -DownloadingMedia)
Assert-OfficeTest ($output.Count -eq 0 -and $script:diskQueries.Count -eq 1) 'A shared staging/install volume must combine reserves once without leaking log messages.'
$script:freeBytes['C:']=16GB-1
Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'C:\Temp\Office' -InstallPaths @('C:\Windows') -DownloadingMedia } 'Insufficient disk space.*before downloading media.*16 GB.*Existing apps have not been removed'
$script:freeBytes['C:']=10GB
$null = & $diskSpaceCheck -Workspace 'C:\Temp\Office' -InstallPaths @('C:\Windows')
$script:freeBytes['C:']=1701MB
Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'C:\Temp\Office' -InstallPaths @('C:\Windows') } 'Insufficient disk space.*after staging, before removal'
$script:freeBytes['C:']=10GB; $script:diskQueries=@()
$null = & $diskSpaceCheck -Workspace 'D:\Temp\Office' -InstallPaths @('C:\Windows','E:\Program Files') -DownloadingMedia
Assert-OfficeTest ($script:diskQueries.Count -eq 3) 'Separate staging, Windows, and application drives must each be checked.'
$script:freeBytes['D:']=5GB
Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'D:\Temp\Office' -InstallPaths @('C:\Windows') -DownloadingMedia } 'Insufficient disk space on D:.*6 GB'
$script:freeBytes['C:']=$null
Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'D:\Temp\Office' -InstallPaths @('C:\Windows') } 'Could not determine free space'
$script:diskReadFails=$true
Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'D:\Temp\Office' -InstallPaths @('C:\Windows') } 'Synthetic disk inventory failure'
}
& {
$script:probeCalls=0; $script:testSleeps=@()
$result = Wait-OfficeResult { $script:probeCalls++; if ($script:probeCalls -eq 3) { [pscustomobject]@{Version='ready'} } } 'delayed fixture registration'
@@ -50,6 +81,12 @@ try {
Assert-OfficeTest ($script:probeCalls -eq 1) 'Failed inventory reads must not be treated as absent installations.'
}
& {
function Write-OfficeSetupDiagnostics {
param($SinceUtc)
$script:diagnosticCalls++
Assert-OfficeTest ($SinceUtc -is [DateTime]) 'ODT diagnostics must use the actual process start time.'
if ($script:diagnosticFails) { throw 'Synthetic locked diagnostic log' }
}
function Start-Process {
param($FilePath,$ArgumentList,$WorkingDirectory,[switch]$Wait,[switch]$PassThru,$WindowStyle,$RedirectStandardOutput,$RedirectStandardError)
$script:processCalls++; $script:processLogs += $RedirectStandardOutput
@@ -68,6 +105,43 @@ try {
Assert-OfficeTest ($code -eq $expectedCode -and $script:processCalls -eq $expectedCalls -and $script:testSleeps.Count -eq ($expectedCalls - 1)) "Incorrect retry behavior for $mode."
Assert-OfficeTest (@($script:processLogs | Select-Object -Unique).Count -eq $expectedCalls) 'MSI retry output logs must not overwrite earlier attempts.'
}
foreach ($script:diagnosticFails in @($false, $true)) {
$script:processExit=17004; $script:diagnosticCalls=0
$output = @(Invoke-OfficeProcess (Join-Path $testRoot 'setup.exe') '/configure inert.xml' (Join-Path $testRoot 'odt-failed'))
Assert-OfficeTest ($output.Count -eq 1 -and $output[0] -eq 17004 -and $script:diagnosticCalls -eq 1) 'ODT native diagnostic collection must retain the original exit code and not pollute output, even when collection fails.'
}
$script:diagnosticFails=$false
foreach ($script:processExit in @(0,3010)) {
$script:diagnosticCalls=0
$null = Invoke-OfficeProcess (Join-Path $testRoot 'setup.exe') '/configure inert.xml' (Join-Path $testRoot 'odt-success')
Assert-OfficeTest ($script:diagnosticCalls -eq 0) 'Successful ODT operations must not search unrelated native logs.'
}
}
& {
$nativeRoot = Join-Path $testRoot 'native-logs'; $null = [IO.Directory]::CreateDirectory($nativeRoot)
$since = [DateTime]::UtcNow.AddMinutes(-1)
$recent = Join-Path $nativeRoot ($env:COMPUTERNAME + '-20261022-test.log')
[IO.File]::WriteAllLines($recent, @('Normal setup entry', 'Click-To-Run Error {"ErrorCode":12345,"ErrorMessage":"Synthetic setup reason"}'))
$old = Join-Path $nativeRoot 'Office-old.log'; [IO.File]::WriteAllText($old, 'Error Old unrelated failure'); [IO.File]::SetLastWriteTimeUtc($old, $since.AddHours(-1))
$unrelated = Join-Path $nativeRoot 'OtherApplication.log'; [IO.File]::WriteAllText($unrelated, 'Error Unrelated app failure')
$empty = Join-Path $nativeRoot 'Office-empty.log'; [IO.File]::WriteAllText($empty, '')
$nested = Join-Path $nativeRoot 'nested'; $null = [IO.Directory]::CreateDirectory($nested)
[IO.File]::WriteAllText((Join-Path $nested 'Office-nested.log'), 'Error Nested unrelated failure')
$output = @(Write-OfficeSetupDiagnostics -SinceUtc $since -SearchRoots @($nativeRoot,$nativeRoot))
Assert-OfficeTest ($output.Count -eq 0) 'Native diagnostics must write through Tools logging without leaking return values.'
$log = Get-Content -LiteralPath $Global:LogFile -Raw
Assert-OfficeTest ($log -match 'Synthetic setup reason' -and $log.Contains($recent)) 'The management log must include the native filename and actual error detail.'
Assert-OfficeTest (([regex]::Matches($log, 'Native Office detail:.*Synthetic setup reason')).Count -eq 1) 'Duplicate search roots must not duplicate diagnostics.'
Assert-OfficeTest ($log -notmatch 'Old unrelated failure|Unrelated app failure|Nested unrelated failure|Office-empty.log') 'Diagnostics must exclude old, unrelated, empty, and nested logs.'
Assert-OfficeTest ((Get-Content -LiteralPath $recent -Raw) -match 'Normal setup entry') 'Collecting native diagnostics must not modify the original log.'
[IO.File]::WriteAllLines($recent, @(1..30 | ForEach-Object { "Error Bounded native detail $_" }))
$null = Write-OfficeSetupDiagnostics -SinceUtc $since -SearchRoots @($nativeRoot)
$log = Get-Content -LiteralPath $Global:LogFile -Raw
Assert-OfficeTest (([regex]::Matches($log, 'Native Office detail: Error Bounded native detail')).Count -eq (Get-OfficeDeploymentDefinitions).SetupDiagnosticErrorLines) 'Native error excerpts must be bounded.'
$null = Write-OfficeSetupDiagnostics -SinceUtc ([DateTime]::UtcNow.AddMinutes(1)) -SearchRoots @($nativeRoot)
Assert-OfficeTest ((Get-Content -LiteralPath $Global:LogFile -Raw) -match 'No recent nonempty native Office logs found') 'Missing native logs must be reported without inventing a diagnosis.'
function Get-Content { throw 'Synthetic native log read failure' }
Assert-OfficeTest (@(Write-OfficeSetupDiagnostics -SinceUtc $since -SearchRoots @($nativeRoot)).Count -eq 0) 'A locked native log must not throw or alter the installer result.'
}
& {
function Invoke-WebRequest {
@@ -276,7 +350,7 @@ try {
if ([IO.Path]::GetFileName($Path) -eq 'odt-download-page.html') {
Assert-OfficeTest ($TimeoutSeconds -eq (Get-OfficeDeploymentDefinitions).OdtPageTimeoutSeconds) 'ODT page must use the retried downloader with its configured timeout.'
[IO.File]::WriteAllText($Path, 'https://download.microsoft.com/test/officedeploymenttool_test.exe')
} elseif ([IO.Path]::GetFileName($Path) -eq 'office-release-history.html') {
} elseif ($Uri -eq (Get-OfficeDeploymentDefinitions).OfficeReleaseHistory) {
Assert-OfficeTest ($Uri -eq (Get-OfficeDeploymentDefinitions).OfficeReleaseHistory) 'Windows 10 release lookup must use Microsoft history.'
[IO.File]::WriteAllText($Path, $script:mediaHistory)
} elseif ([IO.Path]::GetFileName($Path) -eq 'Office-UserCleanup.ps1') {
@@ -315,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.'
$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 (!$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')) {
$mediaWorkspace = Join-Path $testRoot $mode; $null = [IO.Directory]::CreateDirectory($mediaWorkspace)
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Standard'; OfficeArchitecture='64'}
@@ -336,6 +410,12 @@ try {
Assert-OfficeTest (([xml](Get-Content -LiteralPath $media.Config -Raw)).Configuration.Add.Version -eq $media.Version) 'Windows 10 installation must retain the compatible target.'
}
}
$mediaWorkspace = Join-Path $testRoot 'low-space-before-download'; $null = [IO.Directory]::CreateDirectory($mediaWorkspace)
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Standard'; OfficeArchitecture='64'}
$script:mediaProcesses=@()
function Assert-OfficeDiskSpace { param($Workspace,[switch]$DownloadingMedia) Assert-OfficeTest $DownloadingMedia.IsPresent 'A fresh download must include staging space.'; throw 'Synthetic insufficient download space' }
Assert-OfficeThrows { Initialize-OfficeMedia $options $mediaWorkspace } 'Synthetic insufficient download space'
Assert-OfficeTest (!$script:mediaProcesses.Count -and !(Test-Path -LiteralPath (Join-Path $mediaWorkspace 'odt.exe'))) 'Low space must stop before downloading or launching ODT.'
}
& {
$script:staged = @(); $script:verified = @()
@@ -465,14 +545,18 @@ try {
& {
function Get-OfficeSuiteInventory {
$script:removalChecks++
if ($script:removalMode -eq 'empty') { return }
if ($script:removalMode -in @('empty','orphan')) { return }
[pscustomobject]@{DisplayName='Microsoft Office Professional Plus 2016'; WindowsInstaller=1}
if ($script:removalMode -eq 'msi-only') { return }
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'}
}
}
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 {
param($FilePath,$Arguments,$LogPrefix)
$script:removalCalls++; $script:removalStarted=$true
@@ -483,25 +567,26 @@ try {
$removalPath = Join-Path $testRoot 'remove [literal].xml'
(New-OfficeRemovalConfiguration ([pscustomobject]@{OfficeAppShutdown='Force'})).Save($removalPath)
$media = [pscustomobject]@{Setup='inert-setup.exe'; RemovalConfig=$removalPath}
foreach ($script:removalMode in @('empty','msi-only','mixed','delayed','remaining','read-error','fatal','reboot')) {
$script:removalChecks=0; $script:removalCalls=0; $script:removalStarted=$false
$script:removalCode = switch ($script:removalMode) { 'fatal' {1603}; 'reboot' {3010}; default {0} }
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:scrubCalls=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') {
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.'
} elseif ($script:removalMode -eq 'read-error') {
Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'Office inventory is unreadable'
} elseif ($script:removalMode -eq 'fatal') {
Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'ODT Office removal failed \(exit 1603\).*No interactive scrubber was launched.*manual scrub'
} elseif ($script:removalMode -in @('fatal','unknown-17004')) {
Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'ODT Office removal failed.*automatic scrub was not selected'
} else {
$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.'
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.' }
}
$expectedCalls = if ($script:removalMode -in @('empty','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.'
$expectedCalls = if ($script:removalMode -in @('empty','orphan','msi-only')) {0} else {1}
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.'
}
}
& {
@@ -753,85 +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.'
}
# 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)
$source = Join-Path $cacheRoot ('a' * 32); $null = [IO.Directory]::CreateDirectory($source)
# LiteralPath matters: the staged fixture intentionally contains brackets.
foreach ($file in Get-ChildItem -LiteralPath (Join-Path $testRoot 'media [literal]')) { Copy-Item -LiteralPath $file.FullName -Destination $source -Recurse }
$target = Join-Path $cacheRoot ('b' * 32); $null = [IO.Directory]::CreateDirectory($target)
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeArchitecture='64'; COMPANY='New Company'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'}
$script:rejectCacheSignature = $false; $script:helperDownloads = 0
function Get-CimInstance { }
function Assert-OfficeMicrosoftSignature { param($Path) if ($script:rejectCacheSignature) { throw 'Untrusted cache signature' }; Assert-OfficeTest (Test-Path -LiteralPath $Path) 'Cache signature target was missing.' }
function Save-OfficeDownload { param($Uri,$Path) if ([IO.Path]::GetFileName($Path) -ne 'Office-UserCleanup.ps1') { throw 'Unexpected network download on cache hit' }; $script:helperDownloads++; Set-Content -LiteralPath $Path -Value ('# ' + (Get-OfficeDeploymentDefinitions).HelperVersion) }
function Invoke-OfficeProcess { throw 'A cached deployment must not redownload Office.' }
$manifestPath = Join-Path $source 'media-cache.json'
$originalManifest = Get-Content -LiteralPath $manifestPath -Raw
Assert-OfficeTest (!($originalManifest | ConvertFrom-Json).Files[0].PSObject.Properties['Hash']) 'Cache manifests must not store file checksums.'
$different = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5'; OfficeArchitecture='64'}
Assert-OfficeTest (!(Restore-OfficeMediaCache $different $target)) 'Teams selection mismatch reused the wrong cache.'
$different = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeArchitecture='64'; UpdateChannel='MonthlyEnterprise'}
Assert-OfficeTest (!(Restore-OfficeMediaCache $different $target)) 'Channel mismatch reused the wrong cache.'
$different = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeArchitecture='64'}
$different.TargetOfficeVersion='16.0.20326.20158'
Assert-OfficeTest (!(Restore-OfficeMediaCache $different $target)) 'A Windows 10 target reused incompatible unpinned media.'
$manifest = $originalManifest | ConvertFrom-Json; $manifest.Key = Get-OfficeMediaCacheKey $different
$manifest | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $manifestPath
Assert-OfficeTest (!(Restore-OfficeMediaCache $different $target)) 'A matching cache key hid an incompatible Windows 10 payload version.'
$manifest = $originalManifest | ConvertFrom-Json; $manifest.Schema = 1
$manifest | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $manifestPath
Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Old cache manifests must be refreshed under the new version-selection contract.'
$manifest = $originalManifest | ConvertFrom-Json; $manifest.CreatedUtc = [DateTime]::UtcNow.AddDays(-8).ToString('o')
$manifest | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $manifestPath
Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Expired cache was reused.'
Set-Content -LiteralPath $manifestPath -Value $originalManifest
$stream = Join-Path $source 'ODT\Office\Data\16.0.12345.67890\stream.x64.x-none.dat'
$originalBytes = [IO.File]::ReadAllBytes($stream); [IO.File]::WriteAllText($stream, '')
Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Truncated cached media passed the basic size check.'
[IO.File]::WriteAllBytes($stream, $originalBytes)
$extra = Join-Path $source 'ODT\unexpected.dll'; Set-Content -LiteralPath $extra -Value 'unexpected dependency'
Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Unrecorded executable dependencies passed cache verification.'
Remove-OfficeManagedItem $cacheRoot $extra
function Get-CimInstance { [pscustomobject]@{CommandLine="setup.exe $source\install.xml"} }
Assert-OfficeThrows { Restore-OfficeMediaCache $options $target } 'previous Office deployment still has active processes'
Assert-OfficeTest (Test-Path -LiteralPath $stream) 'A live installer lost its cached media.'
function Get-CimInstance { }
$script:rejectCacheSignature = $true
Assert-OfficeTest (!(Restore-OfficeMediaCache $options $target)) 'Invalid Microsoft signature was reused.'
$script:rejectCacheSignature = $false
# Same-size contents are deliberately not hashed; ODT services the payload.
$changedBytes = $originalBytes.Clone(); $changedBytes[0] = $changedBytes[0] -bxor 1; [IO.File]::WriteAllBytes($stream, $changedBytes)
$media = Initialize-OfficeMedia $options $target
Assert-OfficeTest ($media.CachedMediaReused -and $media.Version -eq '16.0.12345.67890' -and $script:helperDownloads -eq 1) 'Deployment did not reuse the validated media and refresh the helper.'
Assert-OfficeTest (!(Test-Path -LiteralPath (Join-Path $source 'ODT')) -and (Test-Path -LiteralPath $media.Setup)) 'Cache transfer duplicated large files or lost setup.'
$config = [xml](Get-Content -LiteralPath $media.Config -Raw)
Assert-OfficeTest ($config.Configuration.AppSettings.Setup.Value -eq 'New Company' -and $config.Configuration.Add.SourcePath -eq (Join-Path $target 'ODT')) 'Reused media retained stale company/configuration paths.'
Assert-OfficeTest (!$config.Configuration.Add.HasAttribute('Version')) 'Reusing ordinary media must not pin the installation version.'
Assert-OfficeTest ((Get-Content -LiteralPath (Join-Path $target 'media-cache.json') -Raw | ConvertFrom-Json).CreatedUtc -eq ($originalManifest | ConvertFrom-Json).CreatedUtc) 'Reuse extended cache expiry.'
Assert-OfficeThrows { Remove-OfficeManagedItem $cacheRoot $testRoot } 'outside the Office deployment root'
Assert-OfficeThrows { Remove-OfficeManagedItem $cacheRoot $cacheRoot } 'outside the Office deployment root'
# Windows 10 refreshes only the small release history and helper on a compatible hit.
$win10Source = Join-Path $cacheRoot ('c' * 32); $null = [IO.Directory]::CreateDirectory($win10Source)
foreach ($file in Get-ChildItem -LiteralPath (Join-Path $testRoot 'win10')) { Copy-Item -LiteralPath $file.FullName -Destination $win10Source -Recurse }
$win10Target = Join-Path $cacheRoot ('d' * 32); $null = [IO.Directory]::CreateDirectory($win10Target)
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Standard'; OfficeArchitecture='64'}
$options.OfficeFeatureRelease = Get-OfficeFeatureRelease -Build 19045 -ProductType 1
$path=Join-Path $testRoot 'Office-corruption.log'
function Get-OfficeSetupLogFiles { Get-Item -LiteralPath $path }
$since=[DateTime]::UtcNow.AddSeconds(-2)
$stamp=[DateTime]::Now.ToString('M/d/yyyy H:mm:ss.fff', [Globalization.CultureInfo]::InvariantCulture)
$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}"}'
Set-Content -LiteralPath $path -Value "$stamp`t$detail"
$evidence=Get-OfficeRemovalCorruptionEvidence $since
Assert-OfficeTest ($evidence.Path -eq $path -and $evidence.Detail.Contains('root\\integration')) 'The observed InvalidDirectory removal error must trigger recovery evidence.'
foreach ($line in @(
('10/22/2026 13:57:00.000' + "`t" + $detail),
("$stamp`t" + $detail.Replace('REMOVEINSTALLATION', 'INSTALL')),
("$stamp`t" + $detail.Replace('InvalidDirectory', 'AccessDenied')),
("$stamp`tSETUP unknown error [ExitCode=17004]"),
('No timestamp ' + $detail),
([DateTime]::Now.AddHours(1).ToString('M/d/yyyy H:mm:ss.fff', [Globalization.CultureInfo]::InvariantCulture) + "`t" + $detail)
)) {
Set-Content -LiteralPath $path -Value $line
Assert-OfficeTest ($null -eq (Get-OfficeRemovalCorruptionEvidence $since)) 'Old, unrelated, unparseable and future evidence must not select recovery.'
}
function Get-Content { throw 'Log locked' }
Assert-OfficeTest ($null -eq (Get-OfficeRemovalCorruptionEvidence $since)) 'Unreadable evidence must not select recovery.'
}
# Download/extract only on demand, validate the Microsoft executable, and never
# rely on Tools.ps1's shadowed Expand-Archive or a previously extracted package.
& {
Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem
$script:scrubPackageMode='single'; $script:scrubSignatures=@(); $script:scrubDownloads=0
function Save-OfficeDownload {
param($Uri,$Path)
switch ([IO.Path]::GetFileName($Path)) {
'office-release-history.html' { [IO.File]::WriteAllText($Path, $releaseHistory) }
'Office-UserCleanup.ps1' { [IO.File]::WriteAllText($Path, '# ' + (Get-OfficeDeploymentDefinitions).HelperVersion) }
default { throw 'Unexpected installer download on Windows 10 cache hit' }
Assert-OfficeTest ($Uri -eq (Get-OfficeDeploymentDefinitions).GetHelpUrl) 'Recovery must use the current Microsoft download link.'
$script:scrubDownloads++
$zip=[IO.Compression.ZipFile]::Open($Path, [IO.Compression.ZipArchiveMode]::Create)
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 ($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.'
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.'
}
# Cleanup runs synchronously on success. Downloads are temporary; pending-user
# helpers have a separate durable folder and are never part of the media cache.
# Get Help's detached signed launcher lives outside the deployment workspace
# 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)
$workspace = Join-Path $root ('c' * 32); $null = [IO.Directory]::CreateDirectory($workspace)
@@ -848,7 +1291,7 @@ try {
}
$media = [pscustomobject]@{Helper=(Join-Path $workspace 'Office-UserCleanup.ps1')}
$userWorkspace = New-OfficeUserWorkspace $media $workspace
Assert-OfficeTest ($media.Helper -eq (Join-Path $userWorkspace 'Office-UserCleanup.ps1') -and (Test-Path -LiteralPath $media.Helper)) 'User helper was not separated from cached installers.'
Assert-OfficeTest (!(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
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'} } }
@@ -857,16 +1300,25 @@ try {
Assert-OfficeTest ($warnings.Count -and (Test-Path -LiteralPath (Join-Path $workspace 'ODT'))) 'Cleanup deleted files referenced by a surviving installer.'
$script:cleanupProcess = $false
$warnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace
Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath $workspace)) 'Successful deployment left its temporary workspace behind.'
Assert-OfficeTest (Test-Path -LiteralPath $media.Helper) 'Temporary cache cleanup deleted the pending-user helper.'
Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath (Join-Path $workspace 'ODT')) -and !(Test-Path -LiteralPath (Join-Path $workspace 'odt.exe')) -and (Test-Path -LiteralPath (Join-Path $workspace 'office-install.stdout.log'))) 'Completion must remove media and preserve diagnostics.'
Assert-OfficeTest (!(Test-Path -LiteralPath $media.Helper) -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
$warnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace
Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath $userWorkspace)) 'Completed user cleanup left its helper folder behind.'
# Older ProgramData stages lose only known downloads, never deferred-user files.
$legacy = Join-Path $userRoot ('d' * 32); $null = [IO.Directory]::CreateDirectory($legacy)
foreach ($name in @('options.json','odt.exe','Office-UserCleanup.ps1','user-cleanup.lock')) { Set-Content -LiteralPath (Join-Path $legacy $name) -Value 'fixture' }
$warnings = Complete-OfficeDeploymentFiles $workspace -PreviousRoot $userRoot
Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath (Join-Path $legacy 'odt.exe')) -and (Test-Path -LiteralPath (Join-Path $legacy 'Office-UserCleanup.ps1'))) 'Legacy download cleanup lost pending-user state or left old downloads.'
# An installer without a source path, locked media and links all defer cleanup.
Assert-OfficeTest (Test-OfficeStagingInUse $workspace @([pscustomobject]@{Name='OfficeC2RClient.exe'})) 'Surviving native installers must defer media cleanup.'
Assert-OfficeThrows { Remove-OfficeManagedItem $root $testRoot } 'outside the Office deployment root'
Assert-OfficeThrows { Remove-OfficeManagedItem $root $root } 'outside the Office deployment root'
$payload=Join-Path $workspace 'odt.exe'; [IO.File]::WriteAllText($payload,'locked')
$handle=[IO.File]::Open($payload,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::None)
try {
$warnings=Complete-OfficeDeploymentFiles $workspace
Assert-OfficeTest ($warnings.Count -gt 0 -and (Test-Path -LiteralPath $payload)) 'In-use payload must survive final cleanup.'
} finally { $handle.Dispose() }
function Get-CimInstance { throw 'Synthetic process inventory failure' }
$warnings=Complete-OfficeDeploymentFiles $workspace
Assert-OfficeTest ($warnings.Count -gt 0 -and (Test-Path -LiteralPath $payload)) 'Unknown process state must retain media.'
}
# The legacy uninstaller must delete both successful and partial downloads.
& {
@@ -892,21 +1344,35 @@ try {
throw "Unexpected object requested by orchestration fixture: $TypeName"
}
function Assert-OfficeDeploymentHost { }
function Complete-OfficeDeploymentFiles { param($Workspace,$UserWorkspace,$PreviousRoot) $script:artifactCleanupRuns++; if ($script:mode -eq 'cleanup-warning') { return ,@('Synthetic file in use') }; return ,@() }
function Assert-OfficeWritablePath { param($Path) [pscustomobject]@{Path=$Path} }
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 Register-ScheduledTask { throw 'Unexpected task registration in orchestration fixture.' }
function New-OfficeWorkspace { $path = Join-Path $testRoot ([guid]::NewGuid().ToString('N')); $null = New-Item -ItemType Directory -Path $path; $path }
function New-OfficeWorkspace { $script:workspaceCreates++; $path = Join-Path $testRoot ([guid]::NewGuid().ToString('N')); $null = New-Item -ItemType Directory -Path $path; $path }
function Start-Transcript { }
function Stop-Transcript { }
function Get-CimInstance { [pscustomobject]@{SID='S-1-5-21-test'; LocalPath=$profile; Special=$false} }
Set-Content -LiteralPath (Join-Path $profile 'NTUSER.DAT') -Value 'test hive, never loaded'
function Stop-OfficeDeploymentApps { $script:events += 'apps' }
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 Initialize-OfficeMedia { param($Options,$Workspace) $script:events += 'download'; if ($script:mode -eq 'download') { throw 'download failure' }; [pscustomobject]@{Version='16.0.1.2'; Helper=(Join-Path $Workspace 'Office-UserCleanup.ps1')} }
function Initialize-OfficeMedia { param($Options,$Workspace) $script:events += 'download'; if ($script:mode -in @('download','download-cleanup')) { throw 'download failure' }; [pscustomobject]@{Version='16.0.1.2'; Helper=(Join-Path $Workspace 'Office-UserCleanup.ps1')} }
function Remove-OfficeCompanionApps { $script:events += 'companions'; if ($script:mode -eq 'companions') { throw 'companion failure' }; return ($script:mode -eq 'reboot') }
function Remove-OfficeSuite { $script:events += 'remove-office'; if ($script:mode -eq 'remove-office') { throw 'Office removal failure' }; if ($script:mode -eq 'office-reboot') { return 3010 }; return 0 }
function 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 Start-OfficeUserCleanup {
$script:events += 'user'; if ($script:mode -eq 'user') { throw 'user still running' }
@@ -920,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'}} }
$script:removalStillRegistered=$false
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'; DeferReboot='false'}
foreach ($script:mode in @('success','download','companions','remove-office','identity','user','phase','install','install-companions','pending','reboot','office-reboot','companion-reboot')) {
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:events = @(); $errorResult = $null; $result = $null
try { $result = Invoke-OfficeDeployment $options } catch { $errorResult = $_ }
@@ -931,14 +1397,34 @@ try {
} else { Assert-OfficeTest ($null -ne $errorResult) "Failure swallowed in $script:mode" }
if ($script:mode -notin @('success','pending','install','install-companions','companion-reboot')) { Assert-OfficeTest ('install' -notin $script:events) "Install ran after $script:mode failure/reboot." }
if ($script:mode -notin @('success','pending','install-companions','companion-reboot')) { Assert-OfficeTest ('install-companions' -notin $script:events) "Companion install ran after $script:mode failure/reboot." }
if ($script:mode -eq 'download') { Assert-OfficeTest ('companions' -notin $script:events -and 'remove-office' -notin $script:events) 'Removal ran after download failed.' }
Assert-OfficeTest ($script:artifactCleanupRuns -eq $(if ($script:mode -in @('success','pending','companion-reboot')) {1} else {0})) "Media cleanup ran before successful installation, or was skipped after success: $script:mode"
if ($script:mode -in @('download','download-cleanup')) { Assert-OfficeTest ('companions' -notin $script:events -and 'remove-office' -notin $script:events) 'Removal ran after download failed.' }
if ($script:mode -eq 'download-cleanup') { Assert-OfficeTest ($errorResult.Exception.Message -eq 'download failure') 'Cleanup replaced the original deployment failure.' }
if ($script:mode -eq 'disk-space') { Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Low space after staging must stop before app shutdown, removal, identity cleanup, and installation.' }
Assert-OfficeTest ($script:artifactCleanupRuns -eq 1) "Finally must attempt media cleanup on every install exit: $script:mode"
if ($script:mode -eq 'office-reboot') { Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'RestartRequiredBeforeInstall' -and 'identity' -notin $script:events -and 'user' -notin $script:events) 'Office removal restart must stop before user cleanup and replacement installation.' }
if ($script:mode -eq 'success') { Assert-OfficeTest (($script:events -join ',') -eq 'download,apps,companions,remove-office,identity,user,phase,install,install-companions') 'Deployment order changed.' }
}
foreach ($deferScrub in @('true','false')) {
$script:mode='scrub-recovery'; $script:events=@()
$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
$script:mode='cleanup-warning'; $script:events=@()
$result = @(Invoke-OfficeDeployment $options)
Assert-OfficeTest ($result.Count -eq 1 -and $result[0].ArtifactCleanupPending -and $result[0].ExitCode -eq 0 -and $result[0].OfficeDeploymentStatus -eq 'Installed') 'Artifact cleanup problems corrupted the receipt or failed a verified installation.'
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')) {
$script:events=@(); $script:artifactCleanupRuns=0
function Install-OfficeMedia { $script:events += 'install'; if ($script:mode -eq 'registration-reboot') { return 3010 }; return 0 }
@@ -969,12 +1455,12 @@ try {
Assert-OfficeTest (!$result.RestartRequired -and $result.ExitCode -eq 0) 'A clean deployment without restart requests must not demand a restart.'
foreach ($shutdown in @('Abort','Force')) {
foreach ($validate in @($null, '', 'true')) {
$script:events=@()
$script:events=@(); $script:workspaceCreates=0; $script:artifactCleanupRuns=0; $script:priorCleanupRuns=0
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeAppShutdown=$shutdown; ValidateBeforeChanges=$validate}
$result = Invoke-OfficeDeployment $options
Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'ValidationPassed' -and $result.ExitCode -eq 0 -and $result.ValidateBeforeChanges) 'Validation did not produce a distinct result.'
Assert-OfficeTest ($result.OfficeRemovalMethod -eq 'SilentODT' -and $result.DeferReboot -is [bool] -and $result.DeferReboot) 'Validation must identify the silent removal method and Boolean restart selection.'
Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Validation reached app shutdown, removal, identities, user tasks, phase changes, or installation.'
Assert-OfficeTest ($script:events.Count -eq 0 -and $script:workspaceCreates -eq 0 -and $script:artifactCleanupRuns -eq 0 -and $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.'
}
}
@@ -982,13 +1468,16 @@ try {
$script:events=@()
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'}
$result = Invoke-OfficeDeployment $options
Assert-OfficeTest (($script:events -join ',') -eq 'download' -and $result.RunningApps[0] -eq 'winword') 'Validation closed a running app with Force selected.'
Assert-OfficeTest ($script:events.Count -eq 0 -and $result.RunningApps[0] -eq 'winword') 'Validation downloaded media or closed a running app with Force selected.'
$options.OfficeAppShutdown='Abort'; $script:events=@()
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Apps are running'
Assert-OfficeTest ($script:events.Count -eq 0) 'Validation did not stop on an Abort prerequisite failure.'
$options.OfficeAppShutdown='Force'; $script:mode='download'; $script:events=@()
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'download failure'
Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Failed validation reached mutations.'
$options.OfficeAppShutdown='Force'; $script:mode='release'; $script:events=@()
$result = Invoke-OfficeDeployment $options
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'
Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'validated Boolean'
$options.ValidateBeforeChanges=$false; $options.DeferReboot='false'; $script:events=@()
@@ -1079,8 +1568,10 @@ __LAUNCH__
Assert-OfficeTest ($probeExitCode -eq $case.Code) "Shim did not propagate workload exit $($case.Code): $probeOutput"
$probeText = $probeOutput | Out-String
if ($case.Mode -eq 'success') {
Assert-OfficeTest ($probeText.IndexOf('{') -ge 0) "Main workload receipt is missing from shim output: $probeText"
$receipt = $probeText.Substring($probeText.IndexOf('{')) | ConvertFrom-Json
# Temp/log paths can contain GUID braces; locate the JSON object's line.
$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.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.'
@@ -1121,8 +1612,11 @@ exit $resultCode
'@
$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'
$ErrorActionPreference='Continue'
$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
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
+708
View File
@@ -0,0 +1,708 @@
#Requires -Version 5.1
# Offline: AST-load cleanup functions; mock shim downloads and native operations.
$ErrorActionPreference = 'Stop'
$repo = Split-Path -Parent $PSScriptRoot
$testRoot = Join-Path $env:TEMP ('SystemCleanupTests-' + [guid]::NewGuid().ToString('N'))
$null = New-Item -ItemType Directory -Path $testRoot
$script:assertions = 0
function Assert-Cleanup { param([bool]$Condition, [string]$Message) $script:assertions++; if (-not $Condition) { throw $Message } }
function Assert-CleanupThrows {
param([scriptblock]$Action, [string]$Pattern)
$caught = $null
try { & $Action | Out-Null } catch { $caught = $_ }
Assert-Cleanup ($null -ne $caught -and $caught.Exception.Message -match $Pattern) "Expected '$Pattern', got '$caught'."
}
function Read-CleanupAst {
param([string]$File)
$tokens = $null; $errors = $null
$ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $repo $File), [ref]$tokens, [ref]$errors)
if ($errors.Count) { throw ($errors | Out-String) }
return $ast
}
function New-CleanupFixture {
param([string]$Relative, [string]$Content = 'fixture', [int]$Days = 60)
$path = Join-Path $testRoot $Relative
$null = [IO.Directory]::CreateDirectory((Split-Path -Parent $path))
[IO.File]::WriteAllText($path, $Content)
[IO.File]::SetLastWriteTimeUtc($path, [datetime]::UtcNow.AddDays(-$Days))
return $path
}
try {
$core = Read-CleanupAst '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)) {
. ([scriptblock]::Create($definition.Extent.Text))
}
# Never contend with a real deployment on the test host.
function New-SystemCleanupOfficeMutex { return [Threading.Mutex]::new($false) }
$messageWriter = ${function:Write-SystemCleanupMessage}
$script:messages = @(); $script:details = @()
function Write-SystemCleanupMessage {
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 {
param([bool]$ReportOnly = $true, [bool]$Server = $false)
return @{
Options = Get-SystemCleanupOptions; OS = [pscustomobject]@{IsServer=$Server; Caption='Fixture'}
Stats=[ordered]@{}; Errors=0
Seen=New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
} | ForEach-Object { $_.Options.ReportOnly=$ReportOnly; $_ }
}
# Defaults and RMM shared scope: values defined outside the loader must survive.
$options = Get-SystemCleanupOptions
Assert-Cleanup ($options.ReportOnly -and $options.TempDays -eq 7 -and $options.DiagnosticDays -eq 30) 'Unsafe defaults.'
Assert-Cleanup ($options.DiskCleanupPreset -eq 'Standard' -and -not $options.ContainsKey('DiskCleanup')) 'Disk Cleanup must use a single selection, defaulting to Standard.'
# Lock down the intended policy: adding handlers changes what operators permit.
$expectedStandard = @('Downloaded Program Files','Internet Cache Files','Thumbnail Cache','Active Setup Temp Folders','Temporary Setup Files','Windows Defender','RetailDemo Offline Content')
$expectedUpdates = @('Service Pack Cleanup','Update Cleanup','Upgrade Discarded Files','Windows Upgrade Log Files')
$expectedDiagnostics = @('Memory Dump Files','Old ChkDsk Files','System error memory dump files','System error minidump files','Setup Log Files','Windows Error Reporting Archive Files','Windows Error Reporting Queue Files','Windows Error Reporting System Archive Files','Windows Error Reporting System Queue Files','Windows Error Reporting Temp Files')
$expectedPresets = [ordered]@{
Standard = $expectedStandard
StandardAndUpdates = @($expectedStandard + $expectedUpdates)
StandardUpdatesAndDiagnostics = @($expectedStandard + $expectedUpdates + $expectedDiagnostics)
All = @(Get-SystemCleanupHandlers)
None = @()
}
foreach ($presetName in $expectedPresets.Keys) {
& {
$CleanupDiskCleanupItems = ' ' + $presetName.ToLowerInvariant() + ' '
$parsed = Get-SystemCleanupOptions
Assert-Cleanup ($parsed.DiskCleanupPreset -ceq $presetName) "Preset normalization failed: $presetName"
Assert-Cleanup (($parsed.DiskCleanupItems -join '|') -ceq ($expectedPresets[$presetName] -join '|')) "Unexpected cleanup scope for $presetName"
Assert-Cleanup ($parsed.DiskCleanupItems -is [array]) "Preset $presetName did not produce an array."
}
}
& {
$CleanupDiskCleanupItems = @(' thumbnail cache ', 'INTERNET CACHE FILES', 'Thumbnail Cache')
$parsed = Get-SystemCleanupOptions
Assert-Cleanup ($parsed.DiskCleanupPreset -eq 'Custom' -and ($parsed.DiskCleanupItems -join ',') -ceq 'Thumbnail Cache,Internet Cache Files') 'Custom arrays must normalize and deduplicate handlers.'
foreach ($invalid in @('Standrad', 'None,Thumbnail Cache', 'Standard,All', 'Standard,Internet Cache Files')) {
$CleanupDiskCleanupItems = $invalid
Assert-CleanupThrows { Get-SystemCleanupOptions } 'Unknown Disk Cleanup preset or item'
}
foreach ($blank in @('', ' ', ',', $null, @())) {
$CleanupDiskCleanupItems = $blank
Assert-CleanupThrows { Get-SystemCleanupOptions } 'cannot be blank'
}
}
& {
foreach ($oldValue in @('false', 'true')) {
$CleanupDiskCleanup = $oldValue
Assert-CleanupThrows { Get-SystemCleanupOptions } 'CleanupDiskCleanup has been removed'
}
}
& {
$CleanupReportOnly = 'false'; $CleanupShadowCopies = ' no '; $CleanupTempDays = '14'
$CleanupDiskCleanupItems = 'Thumbnail Cache,Internet Cache Files'
$o = Get-SystemCleanupOptions
Assert-Cleanup (-not $o.ReportOnly -and -not $o.ShadowCopies -and $o.TempDays -eq 14 -and $o.DiskCleanupItems.Count -eq 2) 'Caller scope/text parsing failed.'
Assert-Cleanup ($CleanupReportOnly -ceq 'false' -and $CleanupTempDays -ceq '14') 'Caller variables were overwritten.'
$CleanupReportOnly = 'maybe'; Assert-CleanupThrows { Get-SystemCleanupOptions } 'must be true or false'
$CleanupReportOnly = $true; $CleanupTempDays = 0; Assert-CleanupThrows { Get-SystemCleanupOptions } 'whole number'
$CleanupTempDays = 7; $CleanupDiskCleanupItems = 'Unknown handler'; Assert-CleanupThrows { Get-SystemCleanupOptions } 'Unknown Disk Cleanup'
}
$legacy = Get-Content -LiteralPath (Join-Path $repo 'Start-Cleanup.ps1') -Raw
$legacyHandlers = @([regex]::Matches($legacy, '"([^"\r\n]+)"\s*=\s*\$(?:true|false);') | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique)
foreach ($handler in $legacyHandlers) { Assert-Cleanup ($handler -in (Get-SystemCleanupHandlers)) "Lost legacy cleanup handler: $handler" }
Assert-Cleanup ($legacyHandlers.Count -eq (Get-SystemCleanupHandlers).Count) 'Unexpected handler inventory mismatch.'
$runCommand = $shim.Find({param($n) $n -is [Management.Automation.Language.CommandAst] -and $n.GetCommandName() -eq 'Run-Script'}, $true)
Assert-Cleanup ($runCommand.Extent.Text -eq 'Run-Script -LivePSScript Start-SystemCleanup') 'Shim must use dot-sourcing Run-Script without Arguments.'
& {
# Exercise the actual shim and real Run-Script with Syncro-style strings.
# Both download implementations return inert source; no real WebClient is created.
$toolsAst=Read-CleanupAst 'Tools.ps1'
$runner=$toolsAst.Find({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq 'Run-Script'}, $true)
$script:cleanupMockTools=$runner.Extent.Text
$fixtureWorkload=New-CleanupFixture 'rmm-scope.ps1' 'Get-SystemCleanupOptions'
function IsURLValid { return $true }
function Download-File { return $fixtureWorkload }
function New-Object {
param($TypeName)
if ($TypeName -ne 'Net.WebClient') { throw "Unexpected object in shim probe: $TypeName" }
$client=[pscustomobject]@{}
$client | Add-Member ScriptMethod DownloadString {
param($URL)
if ($URL -match '/Tools\.ps1$') { return $script:cleanupMockTools }
if ($URL -match '/Start-SystemCleanup\.ps1$') { return 'Get-SystemCleanupOptions' }
throw "Unexpected URL in shim probe: $URL"
}
return $client
}
[string]$CleanupReportOnly='false'
[string]$CleanupSystemTemp='false'
[string]$CleanupTempDays='14'
foreach ($selectionName in @($expectedPresets.Keys) + @('Thumbnail Cache')) {
[string]$CleanupDiskCleanupItems=$selectionName
$output=@(. ([scriptblock]::Create($shim.Extent.Text)))
$selected=@($output | Where-Object { $_ -is [hashtable] })
Assert-Cleanup ($selected.Count -eq 1) 'Shim did not return the inert workload result.'
$injectedOptions=$selected[0]
Assert-Cleanup (-not $injectedOptions.ReportOnly -and -not $injectedOptions.SystemTemp -and $injectedOptions.TempDays -eq 14) 'Run-Script lost Syncro-injected strings.'
$expectedItems = if ($selectionName -eq 'Thumbnail Cache') { @('Thumbnail Cache') } else { @($expectedPresets[$selectionName]) }
Assert-Cleanup (($injectedOptions.DiskCleanupItems -join '|') -ceq ($expectedItems -join '|')) "Run-Script lost the injected selection: $selectionName"
Assert-Cleanup ($injectedOptions.DiagnosticDays -eq 30 -and $CleanupReportOnly -ceq 'false' -and $CleanupTempDays -ceq '14' -and $CleanupDiskCleanupItems -ceq $selectionName) 'Absent defaults or original caller variables changed.'
}
}
# All server/DC gates, including when enabled, and unknown OS failure.
$blocked = @('ShadowCopies','DisableHibernation','CompactSearch','DownloadedExecutables','DuplicateDownloads','OutlookBackups','ITunesBackups','DiskCleanup')
& {
function Get-CimInstance { param($ClassName) if ($ClassName -eq 'Win32_OperatingSystem') { [pscustomobject]@{ProductType=$script:productType; Caption='Fixture OS'} } }
foreach ($script:productType in @(1,2,3)) {
$os = Get-SystemCleanupOS
Assert-Cleanup ($os.IsServer -eq ($script:productType -ne 1)) 'ProductType classification failed.'
$c = New-CleanupContext -Server $os.IsServer
foreach ($name in $blocked) {
if ($name -ne 'DiskCleanup') { $c.Options[$name]=$true }
$script:ran=$false
Invoke-SystemCleanupCategory $c $name { $script:ran=$true }
Assert-Cleanup ($script:ran -eq (-not $os.IsServer)) "Incorrect server gate for $name / $script:productType"
}
}
foreach ($script:productType in @(0,4,$null)) { Assert-CleanupThrows { Get-SystemCleanupOS } 'Cannot identify OS' }
function Get-CimInstance { throw 'Synthetic CIM failure' }
Assert-CleanupThrows { Get-SystemCleanupOS } 'Synthetic CIM failure'
}
$serverContext = New-CleanupContext -Server $true
Assert-CleanupThrows { Invoke-SystemCleanupDiskCleanup $serverContext } 'blocked on server'
Assert-CleanupThrows { Invoke-SystemCleanupShadows $serverContext } 'blocked on server'
Assert-CleanupThrows { Invoke-SystemCleanupSearchCompaction $serverContext } 'blocked on server'
$script:serverAssessmentRan=$false
Invoke-SystemCleanupCategory $serverContext 'ShadowCopies' { $script:serverAssessmentRan=$true }
Assert-Cleanup (-not $script:serverAssessmentRan -and -not $serverContext.Stats.ShadowCopies.Enabled -and $serverContext.Stats.ShadowCopies.Status -eq 'Blocked on server' -and $null -eq $serverContext.Stats.ShadowCopies.CandidateBytes) 'A default-disabled server operation must be listed without assessment.'
& {
function Get-CimInstance { param($ClassName) if ($ClassName -eq 'Win32_OperatingSystem') { [pscustomobject]@{ProductType=3; Caption='Fixture Server'} } }
function Invoke-SystemCleanupDiskCleanup { throw 'SERVER GUARD BYPASSED' }
function Invoke-SystemCleanupShadows { throw 'SERVER GUARD BYPASSED' }
function Invoke-SystemCleanupSearchCompaction { throw 'SERVER GUARD BYPASSED' }
function Invoke-SystemCleanupProcess { throw 'SERVER GUARD BYPASSED' }
# Substitute inert actions so the expanded report cannot inspect host paths.
$dispatcher=${function:Invoke-SystemCleanupCategory}
$script:assessed=@()
function Invoke-SystemCleanupCategory {
param($Context,$Name,$Action)
& $dispatcher $Context $Name { $script:assessed += $Name }
}
$o=Get-SystemCleanupOptions
foreach ($key in @($o.Keys)) { if ($o[$key] -is [bool]) { $o[$key]=$false } }
$o.ReportOnly=$true
foreach ($name in $blocked) { if ($name -ne 'DiskCleanup') { $o[$name]=$true } }
$result = @(Invoke-SystemCleanup $o)
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.'
}
# None is disabled in reports and apply; every nonempty preset remains blocked
# on both server types. No host inventories, registry operations or native calls.
foreach ($server in @($false, $true)) {
foreach ($reportOnly in @($false, $true)) {
foreach ($presetName in $expectedPresets.Keys) {
& {
$CleanupDiskCleanupItems = $presetName
$c = New-CleanupContext -Server $server -ReportOnly $reportOnly
$script:ran = $false
Invoke-SystemCleanupCategory $c 'DiskCleanup' { $script:ran = $true }
$shouldRun = -not $server -and ($reportOnly -or $presetName -ne 'None')
Assert-Cleanup ($script:ran -eq $shouldRun) "Incorrect Disk Cleanup dispatch: $presetName / server=$server / report=$reportOnly"
if ($reportOnly) {
Assert-Cleanup ($c.Stats.DiskCleanup.Enabled -eq ($presetName -ne 'None')) 'Disk Cleanup enablement must follow its selection.'
Assert-Cleanup ($c.Stats.DiskCleanup.Setting -ceq "CleanupDiskCleanupItems=$presetName") 'Report must identify the real operator setting.'
if ($server) { Assert-Cleanup ($c.Stats.DiskCleanup.Status -eq 'Blocked on server') 'Presets must not bypass the server block.' }
}
}
}
}
}
& {
$CleanupDiskCleanupItems = 'None'
$c = New-CleanupContext
function Get-ChildItem { throw 'None must not access the registry.' }
function Test-SystemCleanupAppRunning { throw 'None must not probe native cleanup.' }
function Invoke-SystemCleanupProcess { throw 'None must not launch cleanmgr.' }
$script:messages = @(); $script:details = @()
Invoke-SystemCleanupCategory $c 'DiskCleanup' { Invoke-SystemCleanupDiskCleanup $c }
Write-SystemCleanupReport $c
$report = $script:messages -join "`n"
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 (($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
Invoke-SystemCleanupDiskCleanup $c
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.
$root=Join-Path $testRoot 'temps'
$old=New-CleanupFixture 'temps\old[1].tmp'
$fresh=New-CleanupFixture 'temps\parent\fresh.tmp' 'fresh' 0
$nestedOld=New-CleanupFixture 'temps\parent\old.tmp'
[IO.Directory]::SetLastWriteTimeUtc((Split-Path -Parent $fresh), [datetime]::UtcNow.AddDays(-90))
$cutoff=[datetime]::UtcNow.AddDays(-7)
$c=New-CleanupContext
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
Assert-Cleanup ($c.Stats.SystemTemp.CandidateFiles -eq 2 -and $c.Stats.SystemTemp.RemovedFiles -eq 0) 'Preview counts incorrect.'
Assert-Cleanup ((Test-Path -LiteralPath $old) -and (Test-Path -LiteralPath $nestedOld) -and (Test-Path -LiteralPath $fresh)) 'Preview changed files.'
$c=New-CleanupContext -ReportOnly $false
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
Assert-Cleanup (-not (Test-Path -LiteralPath $old) -and -not (Test-Path -LiteralPath $nestedOld) -and (Test-Path -LiteralPath $fresh)) 'Age/leaf deletion failure.'
Assert-Cleanup ($c.Stats.SystemTemp.RemovedFiles -eq 2) 'Removed files were not counted.'
# Disabled categories get independent report estimates, even when files overlap an
# enabled category later in the run. Apply mode still ignores disabled categories.
$potentialRoot=Join-Path $testRoot 'potential'
$potentialOriginal=New-CleanupFixture 'potential\install.exe' 'abc'
$potentialDuplicate=New-CleanupFixture 'potential\install (1).exe' 'abc'
$potentialRecent=New-CleanupFixture 'potential\recent.exe' 'fresh' 0
$c=New-CleanupContext
$c.Options.DownloadedExecutables=$false; $c.Options.DuplicateDownloads=$true
Invoke-SystemCleanupCategory $c 'DownloadedExecutables' { Clear-SystemCleanupTree $c 'DownloadedExecutables' $potentialRoot $cutoff -Include @('*.exe') }
Invoke-SystemCleanupCategory $c 'DuplicateDownloads' { Remove-SystemCleanupDuplicates $c $potentialRoot $cutoff }
Assert-Cleanup (-not $c.Stats.DownloadedExecutables.Enabled -and $c.Stats.DownloadedExecutables.CandidateFiles -eq 2 -and $c.Stats.DownloadedExecutables.CandidateBytes -eq 6) 'Disabled download estimate is missing or includes recent files.'
Assert-Cleanup ($c.Stats.DuplicateDownloads.Enabled -and $c.Stats.DuplicateDownloads.CandidateFiles -eq 1 -and $c.Stats.DuplicateDownloads.CandidateBytes -eq 3) 'Disabled preview consumed an enabled category candidate.'
Assert-Cleanup (-not $c.Options.DownloadedExecutables -and (Test-Path -LiteralPath $potentialDuplicate)) 'Preview enabled a disabled option or deleted data.'
$totals=Get-SystemCleanupReportTotals $c
Assert-Cleanup ($totals.EnabledBytes -eq 3 -and $totals.EnabledFiles -eq 1 -and $totals.AdditionalDisabledBytes -eq 3 -and $totals.AdditionalDisabledFiles -eq 1) 'Overlapping report totals double-counted a file.'
$script:messages=@()
Write-SystemCleanupReport $c
$report=$script:messages -join "`n"
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
$script:disabledRan=$false
Invoke-SystemCleanupCategory $c 'DownloadedExecutables' { $script:disabledRan=$true; Clear-SystemCleanupTree $c 'DownloadedExecutables' $potentialRoot $cutoff -Include @('*.exe') }
Assert-Cleanup (-not $script:disabledRan -and (Test-Path -LiteralPath $potentialOriginal) -and (Test-Path -LiteralPath $potentialDuplicate) -and (Test-Path -LiteralPath $potentialRecent)) 'Apply mode ran a disabled category.'
$outside=New-CleanupFixture 'outside\preserved.tmp'
Assert-Cleanup (-not (Test-SystemCleanupPath $outside $root)) 'Containment check accepted an outside file.'
Assert-Cleanup (-not (Test-SystemCleanupPath 'C:\Windows' 'C:\')) 'Drive-root cleanup must be rejected.'
$junction=Join-Path $root 'linked'
$null=New-Item -ItemType Junction -Path $junction -Target (Split-Path -Parent $outside)
try {
Assert-Cleanup (-not (Test-SystemCleanupPath (Join-Path $junction 'preserved.tmp') $root)) 'Linked ancestor was accepted.'
$c=New-CleanupContext -ReportOnly $false
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
Assert-Cleanup (Test-Path -LiteralPath $outside) 'Cleanup followed junction outside the target.'
} finally { [IO.Directory]::Delete($junction, $false) }
$locked=New-CleanupFixture 'temps\locked.tmp'
$lock=[IO.File]::Open($locked, 'Open', 'ReadWrite', 'None')
try {
$c=New-CleanupContext -ReportOnly $false
Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' $root $cutoff -Recurse }
Assert-Cleanup ((Test-Path -LiteralPath $locked) -and $c.Stats.SystemTemp.FailedFiles -eq 1) 'Locked files must be retained and counted.'
} finally { $lock.Dispose() }
# Same length is not the same content, and extensions must match.
$null=New-CleanupFixture 'downloads\a.txt' 'abc'
$same=New-CleanupFixture 'downloads\a (1).txt' 'abc'
$different=New-CleanupFixture 'downloads\a (2).txt' 'xyz'
$extension=New-CleanupFixture 'downloads\a (1).csv' 'abc'
$recent=New-CleanupFixture 'downloads\a (3).txt' 'abc' 0
$c=New-CleanupContext -ReportOnly $false; $c.Options.DuplicateDownloads=$true
Invoke-SystemCleanupCategory $c 'DuplicateDownloads' { Remove-SystemCleanupDuplicates $c (Join-Path $testRoot 'downloads') $cutoff }
Assert-Cleanup (-not (Test-Path -LiteralPath $same) -and (Test-Path -LiteralPath $different) -and (Test-Path -LiteralPath $extension) -and (Test-Path -LiteralPath $recent)) 'Duplicate matching/retention failure.'
# Entire backup retained when a nested file is recent; old complete unit removed.
$backupOld=New-CleanupFixture 'backups\phone\old.dat'
$backupFresh=New-CleanupFixture 'backups\phone\nested\new.dat' 'new' 0
$bundle=Split-Path -Parent $backupOld
[IO.Directory]::SetLastWriteTimeUtc($bundle, [datetime]::UtcNow.AddDays(-60))
$c=New-CleanupContext -ReportOnly $false; $c.Options.ITunesBackups=$true
Invoke-SystemCleanupCategory $c 'ITunesBackups' { Remove-SystemCleanupBundle $c 'ITunesBackups' $bundle $cutoff }
Assert-Cleanup ((Test-Path -LiteralPath $backupOld) -and (Test-Path -LiteralPath $backupFresh)) 'Recent backup was partially cleaned.'
[IO.File]::SetLastWriteTimeUtc($backupFresh,[datetime]::UtcNow.AddDays(-60))
[IO.Directory]::SetLastWriteTimeUtc((Split-Path -Parent $backupFresh),[datetime]::UtcNow.AddDays(-60))
$backupLock=[IO.File]::Open($backupFresh,'Open','ReadWrite','None')
try {
$c=New-CleanupContext -ReportOnly $false; $c.Options.ITunesBackups=$true
Invoke-SystemCleanupCategory $c 'ITunesBackups' { Remove-SystemCleanupBundle $c 'ITunesBackups' $bundle $cutoff }
Assert-Cleanup ((Test-Path -LiteralPath $backupOld) -and (Test-Path -LiteralPath $backupFresh)) 'Locked backup was partially cleaned.'
} finally { $backupLock.Dispose() }
$c=New-CleanupContext -ReportOnly $false; $c.Options.ITunesBackups=$true
Invoke-SystemCleanupCategory $c 'ITunesBackups' { Remove-SystemCleanupBundle $c 'ITunesBackups' $bundle $cutoff }
Assert-Cleanup (-not (Test-Path -LiteralPath $bundle)) 'Old backup unit was not completely removed.'
# $I metadata controls retention, NOT the payload's old modification time.
$recycle=Join-Path $testRoot 'recycle'
foreach ($case in @(@{Id='old'; Days=60; Version=2},@{Id='recent'; Days=0; Version=1},@{Id='unknown'; Days=60; Version=99})) {
$meta=New-CleanupFixture ('recycle\S-1-5-21-fixture\$I'+$case.Id) 'placeholder'
$null=New-CleanupFixture ('recycle\S-1-5-21-fixture\$R'+$case.Id) 'data'
$originalPath=[Text.Encoding]::Unicode.GetBytes("C:\fixture.txt`0")
$length=if ($case.Version -eq 1) {544} else {28+$originalPath.Length}
$bytes=New-Object byte[] $length
[BitConverter]::GetBytes([long]$case.Version).CopyTo($bytes,0)
[BitConverter]::GetBytes([long]4).CopyTo($bytes,8)
[BitConverter]::GetBytes([datetime]::UtcNow.AddDays(-$case.Days).ToFileTimeUtc()).CopyTo($bytes,16)
if ($case.Version -eq 1) { $originalPath.CopyTo($bytes,24) }
else {
[BitConverter]::GetBytes([uint32]($originalPath.Length/2)).CopyTo($bytes,24)
$originalPath.CopyTo($bytes,28)
}
[IO.File]::WriteAllBytes($meta,$bytes)
}
$c=New-CleanupContext -ReportOnly $false; $c.Options.RecycleBin=$true
Invoke-SystemCleanupCategory $c 'RecycleBin' { Clear-SystemCleanupRecycleBin $c $recycle $cutoff }
Assert-Cleanup (-not (Test-Path -LiteralPath (Join-Path $recycle 'S-1-5-21-fixture\$Rold')) -and -not (Test-Path -LiteralPath (Join-Path $recycle 'S-1-5-21-fixture\$Iold'))) 'Old recycled pair not removed.'
foreach ($id in @('recent','unknown')) {
Assert-Cleanup ((Test-Path -LiteralPath (Join-Path $recycle ('S-1-5-21-fixture\$I'+$id))) -and (Test-Path -LiteralPath (Join-Path $recycle ('S-1-5-21-fixture\$R'+$id)))) "Unsafe recycle deletion: $id"
}
$truncated=New-CleanupFixture 'truncated-recycle-metadata' 'data'
[IO.File]::WriteAllBytes($truncated, [byte[]]@(2,0,0,0,0,0,0,0))
Assert-CleanupThrows { Get-SystemCleanupRecycleDate $truncated } 'Truncated'
# Native failure is observable; preview never starts a process.
& {
$script:starts=0
function Start-Process { param($FilePath,$ArgumentList,$WindowStyle,[switch]$Wait,[switch]$PassThru)
$script:starts++; Assert-Cleanup ($Wait -and $PassThru -and $WindowStyle -eq 'Hidden') 'Native operations must wait, capture exit status, and hide the window.'
[pscustomobject]@{ExitCode=5}
}
$c=New-CleanupContext
Invoke-SystemCleanupProcess $c 'powercfg.exe' '/hibernate off'
Assert-Cleanup ($script:starts -eq 0) 'Report mode launched a native process.'
$c.Options.ReportOnly=$false
Assert-CleanupThrows { Invoke-SystemCleanupProcess $c 'powercfg.exe' '/hibernate off' } 'exit code 5'
}
# cleanmgr only writes selected handlers in an unused slot; finally restores after failure.
& {
$script:events=@(); $script:nativeFailure=$false
function Test-SystemCleanupAppRunning { return $false }
function Get-ChildItem {
param($LiteralPath)
foreach ($name in @('Thumbnail Cache','Previous Installations')) {
$key=[pscustomobject]@{PSChildName=$name; PSPath=('fixture:\'+$name)}
$key | Add-Member ScriptMethod GetValueNames { @('StateFlags1000') }
$key
}
}
function New-ItemProperty { param($LiteralPath,$Name,$Value,$PropertyType) $script:events += "write:$LiteralPath/$Name=$Value" }
function Remove-ItemProperty { param($LiteralPath,$Name) $script:events += "remove:$LiteralPath/$Name" }
function Invoke-SystemCleanupProcess { param($Context,$FileName,$Arguments) $script:events += "run:$FileName $Arguments"; if ($script:nativeFailure) { throw 'Synthetic native failure' } }
$c=New-CleanupContext; $c.Options.DiskCleanupItems=@('Thumbnail Cache'); $c.Options.DiskCleanupPreset='Custom'
Invoke-SystemCleanupDiskCleanup $c
Assert-Cleanup ($script:events.Count -eq 0) 'Report mode wrote Disk Cleanup settings.'
$c.Options.ReportOnly=$false
foreach ($script:nativeFailure in @($false,$true)) {
$script:events=@()
if ($script:nativeFailure) { Assert-CleanupThrows { Invoke-SystemCleanupDiskCleanup $c } 'Synthetic native failure' }
else { Invoke-SystemCleanupDiskCleanup $c }
Assert-Cleanup ($script:events.Count -eq 3 -and $script:events[0] -eq 'write:fixture:\Thumbnail Cache/StateFlags1001=2' -and $script:events[1] -eq 'run:cleanmgr.exe /sagerun:1001' -and $script:events[2] -eq 'remove:fixture:\Thumbnail Cache/StateFlags1001') 'Disk Cleanup settings selection/restoration failed.'
}
}
# Snapshot deletion is exact-ID based and retains the newest system-volume snapshot.
& {
$script:commands=@()
function Get-CimInstance {
param($ClassName)
if ($ClassName -eq 'Win32_Volume') { [pscustomobject]@{DriveLetter=$env:SystemDrive; DeviceID='volume1'} }
else {
[pscustomobject]@{VolumeName='volume1'; 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='volume2'; InstallDate=[datetime]'2026-09-01'; ID='{33333333-3333-3333-3333-333333333333}'}
}
}
function Invoke-SystemCleanupProcess { param($Context,$FileName,$Arguments) $script:commands += "$FileName $Arguments" }
Invoke-SystemCleanupShadows (New-CleanupContext)
Assert-Cleanup ($script:commands.Count -eq 1 -and $script:commands[0] -match '/Shadow=\{11111111-' -and $script:commands[0] -notmatch '/Oldest') 'Incorrect VSS target selection.'
}
# Search always restores running state after failure, never changes startup settings.
& {
$savedProgramData=$env:ProgramData
$null=New-CleanupFixture 'search\Microsoft\Search\Data\Applications\Windows\Windows.edb'
try {
$env:ProgramData=Join-Path $testRoot 'search'
$script:serviceEvents=@()
function Get-Service {
param($Name)
$s=[pscustomobject]@{Status=$script:originalServiceStatus}
$s | Add-Member ScriptMethod WaitForStatus { param($Status,$Timeout) $script:serviceEvents += 'wait' }
return $s
}
function Stop-Service { param($Name) $script:serviceEvents += 'stop' }
function Start-Service { param($Name) $script:serviceEvents += 'start' }
function Set-Service { throw 'Startup configuration must be preserved.' }
function Invoke-SystemCleanupProcess { param($Context,$FileName,$Arguments) $script:serviceEvents += 'compact'; throw 'Synthetic compaction failure' }
foreach ($script:originalServiceStatus in @('Running','Stopped')) {
$script:serviceEvents=@()
$c=New-CleanupContext -ReportOnly $false
Assert-CleanupThrows { Invoke-SystemCleanupSearchCompaction $c } 'Synthetic compaction failure'
$expected=if ($script:originalServiceStatus -eq 'Running') { 'stop,wait,compact,start' } else { 'compact' }
Assert-Cleanup (($script:serviceEvents -join ',') -eq $expected) 'Search service restoration failed.'
}
$script:serviceEvents=@()
Invoke-SystemCleanupSearchCompaction (New-CleanupContext)
Assert-Cleanup ($script:serviceEvents.Count -eq 0) 'Preview changed Search service state.'
} finally { $env:ProgramData=$savedProgramData }
}
# Entire entry point with mixed enablement in preview. All mutation APIs fail
# the test if called. Every environment path and inventory points at inert fixtures.
& {
$savedEnvironment=@{SystemRoot=$env:SystemRoot; SystemDrive=$env:SystemDrive; ProgramData=$env:ProgramData}
$previewRoot=Join-Path $testRoot 'preview'
$null=New-CleanupFixture 'preview\Windows\Temp\old.tmp'
$null=New-CleanupFixture 'preview\Windows\Temp\CbsPersist_fixture.log'
$null=New-CleanupFixture 'preview\Users\Alice\AppData\Local\Temp\old.tmp'
$null=New-CleanupFixture 'preview\Users\Alice\Downloads\install.exe'
$null=New-CleanupFixture 'preview\hiberfil.sys'
foreach ($exe in @('powercfg.exe','schtasks.exe','esentutl.exe','vssadmin.exe','cleanmgr.exe')) { $null=New-CleanupFixture ('preview\Windows\System32\'+$exe) 'inert, never executed' }
try {
$env:SystemRoot=Join-Path $previewRoot 'Windows'; $env:SystemDrive=$previewRoot
$env:ProgramData=Join-Path $previewRoot 'ProgramData'
function Get-CimInstance {
param($ClassName)
switch ($ClassName) {
Win32_OperatingSystem { [pscustomobject]@{ProductType=1; Caption='Fixture Client'} }
Win32_UserProfile { [pscustomobject]@{Special=$false; LocalPath=(Join-Path $previewRoot 'Users\Alice')} }
Win32_Volume { [pscustomobject]@{DriveLetter=$env:SystemDrive; DeviceID='\\?\Volume{11111111-1111-1111-1111-111111111111}\'} }
Win32_ShadowCopy {
[pscustomobject]@{VolumeName='\\?\Volume{11111111-1111-1111-1111-111111111111}\'; InstallDate=[datetime]'2026-10-01'; ID='{11111111-1111-1111-1111-111111111111}'}
[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 Get-SystemCleanupOfficeStagingRoots { return (Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment') }
function Get-Service { [pscustomobject]@{Status='Stopped'} }
function Remove-Item { throw 'PREVIEW MUTATION: Remove-Item' }
function New-ItemProperty { throw 'PREVIEW MUTATION: registry write' }
function Remove-ItemProperty { throw 'PREVIEW MUTATION: registry removal' }
function Start-Service { throw 'PREVIEW MUTATION: start service' }
function Stop-Service { throw 'PREVIEW MUTATION: stop service' }
function Delete-DeliveryOptimizationCache { throw 'PREVIEW MUTATION: delivery cache' }
function Start-Process { throw 'PREVIEW MUTATION: native program' }
$o=Get-SystemCleanupOptions
$script:messages=@(); $script:details=@()
$result=@(Invoke-SystemCleanup $o)
Assert-Cleanup ($result.Count -eq 23 -and @($result | Where-Object Status -ne 'Preview').Count -eq 0) "Full preview did not cover every category (count=$($result.Count))."
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'DownloadedExecutables' -and -not $_.Enabled -and $_.CandidateFiles -eq 1 }).Count -eq 1) 'Default-disabled downloads were not assessed by the entry point.'
Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'ComponentStore' -and -not $_.Enabled -and $null -eq $_.CandidateBytes -and $_.EstimateStatus -eq 'Not estimated' }).Count -eq 1) 'Unknown native savings must not be reported as zero.'
Assert-Cleanup (Test-Path -LiteralPath (Join-Path $env:SystemRoot 'Temp\old.tmp')) 'Full preview removed a fixture.'
$compactOutput = ($script:messages | ForEach-Object { '[SystemCleanup] ' + $_ }) -join "`r`n"
$script:compactReportBytes = [Text.Encoding]::UTF8.GetByteCount($compactOutput)
Assert-Cleanup ($script:compactReportBytes -lt 4096) "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 Get-Command { return $null }
$o.DiskCleanupItems=@(); $o.DiskCleanupPreset='None'
$script:messages=@()
$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 '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 {
$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))."
} finally {
# Only this test's generated directory; links are removed non-recursively above.
$resolved=[IO.Path]::GetFullPath($testRoot)
$expectedParent=[IO.Path]::GetFullPath($env:TEMP).TrimEnd('\')+'\'
if (-not $resolved.StartsWith($expectedParent,[StringComparison]::OrdinalIgnoreCase) -or (Split-Path -Leaf $resolved) -notmatch '^SystemCleanupTests-[0-9a-f]{32}$') { throw 'Unsafe fixture cleanup path.' }
if (Test-Path -LiteralPath $resolved) { Remove-Item -LiteralPath $resolved -Recurse -Force }
}
+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"
}