fix more issues with the scrubber and product install status

This commit is contained in:
2026-10-30 15:35:38 -04:00
parent 0c614596f8
commit f2830cb10a
8 changed files with 474 additions and 59 deletions
+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 }
+65 -34
View File
@@ -846,8 +846,8 @@ function Get-OfficeSuiteInventory {
} }
function Get-OfficeClickToRunState { function Get-OfficeClickToRunState {
# Finished-product inventory misses interrupted installations. Read servicing # Servicing metadata is diagnostic evidence, not installed-product inventory.
# state as evidence only; ODT, not registry deletion, must remove the old setup. # A service can survive removal, and successful installs retain source URLs.
$root = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun' $root = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun'
$present = Test-Path -LiteralPath $root -ErrorAction Stop $present = Test-Path -LiteralPath $root -ErrorAction Stop
$sources = @(); $working = @() $sources = @(); $working = @()
@@ -869,18 +869,14 @@ function Get-OfficeClickToRunState {
[pscustomobject]@{ Present=($present -or $null -ne $service); SourceReferences=$sources; WorkingConfiguration=$working } [pscustomobject]@{ Present=($present -or $null -ne $service); SourceReferences=$sources; WorkingConfiguration=$working }
} }
function Test-OfficeFreshInstallState { function Assert-OfficeRemovalComplete {
[bool](Wait-OfficeResult { param([string]$Workspace)
$state = Get-OfficeClickToRunState $idle = Wait-OfficeResult { !(Test-OfficeStagingInUse $Workspace @(Get-CimInstance Win32_Process -ErrorAction Stop)) } 'Office installation/removal workers to finish before replacement'
!$state.SourceReferences.Count -and !$state.WorkingConfiguration.Count if (!$idle) { throw 'Office installation/removal workers are still running. Installation stopped to avoid overlapping operations.' }
} 'removal of previous Click-to-Run working configuration and deployment source references') $remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 })
} if ($remaining.Count) { throw "Click-to-Run products remain before replacement: $($remaining.DisplayName -join '; '). Installation stopped." }
$state = Get-OfficeClickToRunState
function Assert-OfficeFreshInstallState { $null = Write-Output "Office removal verified: no registered Click-to-Run products or active installer workers. Diagnostic metadata: $($state.SourceReferences.Count) staging references; working configuration: $($state.WorkingConfiguration -join ', '). Metadata alone does not require removal; ODT will configure this run's fresh media."
if (!(Test-OfficeFreshInstallState)) {
$state = Get-OfficeClickToRunState
throw "Click-to-Run still retains previous deployment state after ODT removal. Installation stopped to prevent reuse of old content. Working configuration: $($state.WorkingConfiguration -join ', '). Source references: $($state.SourceReferences -join '; '). Arrange an attended Office repair/scrub: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)"
}
} }
function Get-OfficeRemovalCorruptionEvidence { function Get-OfficeRemovalCorruptionEvidence {
@@ -992,12 +988,46 @@ function Open-OfficeScrubWorkerHandle {
} }
} }
function Get-OfficeScrubReportRoots {
param($Worker)
try {
$owner = Invoke-CimMethod -InputObject $Worker -MethodName GetOwnerSid -ErrorAction Stop
if ($owner.ReturnValue -ne 0 -or !$owner.Sid) { throw 'Worker owner SID is unavailable.' }
if ($owner.Sid -eq 'S-1-5-18') {
"$env:WINDIR\System32\config\systemprofile\AppData\Local\DAFs"
"$env:WINDIR\SysWOW64\config\systemprofile\AppData\Local\DAFs"
} else {
$profile = Get-ItemPropertyValue -LiteralPath "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$($owner.Sid)" -Name ProfileImagePath -ErrorAction Stop
Join-Path ([Environment]::ExpandEnvironmentVariables($profile)) 'AppData\Local\DAFs'
}
} catch { $null = Write-Output "Could not locate diagnostic reports for scrub worker PID $($Worker.ProcessId): $($_.Exception.Message). Process and product verification remain required." }
}
function Read-OfficeScrubWorkerReport {
param($Worker, [string[]]$Roots)
foreach ($root in $Roots) {
try {
if (!(Test-Path -LiteralPath $root -ErrorAction Stop)) { continue }
foreach ($file in @(Get-ChildItem -LiteralPath $root -Filter 'cse.amplify.diagaction.gethelp.officeuninstallalda_*.log' -File -ErrorAction Stop)) {
# Only fresh reports in this worker's account. Never apply an older
# scrub's failure to the current run or use a report to kill a worker.
if ($file.CreationTimeUtc -lt ([datetime]$Worker.CreationDate).ToUniversalTime() -or $file.LastWriteTimeUtc -lt ([datetime]$Worker.CreationDate).ToUniversalTime() -or $file.Length -gt 1MB) { continue }
$text = Get-Content -LiteralPath $file.FullName -Raw -ErrorAction Stop
if ($text -notmatch '(?s)\bReport:\s*(\{.*\})\s*$') { continue }
try { $report = $Matches[1] | ConvertFrom-Json -ErrorAction Stop } catch { continue } # It may still be being written.
if ($report.TroubleshooterName -ne 'GH_OfficeUninstallALDA' -or !$report.ExecutionResult) { continue }
[pscustomobject]@{ Path=$file.FullName; Result=$report.ExecutionResult; Detail=$report.ExecutionResultDetails }
}
} catch { $null = Write-Output "Could not read scrub reports in ${root}: $($_.Exception.Message)." }
}
}
function Wait-OfficeScrubRemoval { function Wait-OfficeScrubRemoval {
param([object[]]$ExistingWorkers) param([object[]]$ExistingWorkers)
$definitions = Get-OfficeDeploymentDefinitions $definitions = Get-OfficeDeploymentDefinitions
$baseline = @{}; $handles = @{}; $quietChecks = 0; $lastState = $null; $observedWorker = $false $baseline = @{}; $handles = @{}; $quietChecks = 0; $lastState = $null; $observedWorker = $false
foreach ($worker in $ExistingWorkers) { $baseline["$($worker.ProcessId)|$(([datetime]$worker.CreationDate).ToUniversalTime().Ticks)"] = $true } foreach ($worker in $ExistingWorkers) { $baseline["$($worker.ProcessId)|$(([datetime]$worker.CreationDate).ToUniversalTime().Ticks)"] = $true }
$null = Write-Output "Get Help started background removal. Waiting up to $([int](($definitions.ScrubBackgroundCheckAttempts - 1) * $definitions.ScrubBackgroundCheckSeconds / 60)) minutes for workers, Office registrations and previous deployment state to clear, followed by a $([int](($definitions.ScrubBackgroundQuietChecks - 1) * $definitions.ScrubBackgroundCheckSeconds))-second quiet interval." $null = Write-Output "Get Help started background removal. Waiting up to $([int](($definitions.ScrubBackgroundCheckAttempts - 1) * $definitions.ScrubBackgroundCheckSeconds / 60)) minutes for workers and Office registrations to clear, followed by a $([int](($definitions.ScrubBackgroundQuietChecks - 1) * $definitions.ScrubBackgroundCheckSeconds))-second quiet interval."
$null = Write-Output "Leave the Microsoft cleanup window open until it reports completion. If it says 'Press any key to exit', dismiss that completed prompt to let verification continue. Closing it during removal can fail deployment." $null = Write-Output "Leave the Microsoft cleanup window open until it reports completion. If it says 'Press any key to exit', dismiss that completed prompt to let verification continue. Closing it during removal can fail deployment."
try { try {
for ($attempt = 1; $attempt -le $definitions.ScrubBackgroundCheckAttempts; $attempt++) { for ($attempt = 1; $attempt -le $definitions.ScrubBackgroundCheckAttempts; $attempt++) {
@@ -1011,13 +1041,16 @@ function Wait-OfficeScrubRemoval {
if ($worker.CommandLine -notmatch '(?i)(OffScrub|OfficeScrub|OfficeUninstall|GetHelpElevated)') { continue } if ($worker.CommandLine -notmatch '(?i)(OffScrub|OfficeScrub|OfficeUninstall|GetHelpElevated)') { continue }
$identity = "$($worker.ProcessId)|$(([datetime]$worker.CreationDate).ToUniversalTime().Ticks)" $identity = "$($worker.ProcessId)|$(([datetime]$worker.CreationDate).ToUniversalTime().Ticks)"
if (!$handles.ContainsKey($identity)) { if (!$handles.ContainsKey($identity)) {
$handles[$identity] = [pscustomobject]@{ Process=(Open-OfficeScrubWorkerHandle $worker); Checked=$false; Id=$worker.ProcessId } $handles[$identity] = [pscustomobject]@{ Process=(Open-OfficeScrubWorkerHandle $worker); Checked=$false; Id=$worker.ProcessId; Worker=$worker; ReportRoots=@(Get-OfficeScrubReportRoots $worker) }
$observedWorker = $true $observedWorker = $true
$null = Write-Output "Monitoring scrub worker $($worker.Name), PID $($worker.ProcessId), created $($worker.CreationDate). Command: $($worker.CommandLine)" $null = Write-Output "Monitoring scrub worker $($worker.Name), PID $($worker.ProcessId), created $($worker.CreationDate). Command: $($worker.CommandLine)"
} }
} }
$liveHandles = 0 $liveHandles = 0
foreach ($watch in $handles.Values) { foreach ($watch in $handles.Values) {
foreach ($report in @(Read-OfficeScrubWorkerReport $watch.Worker $watch.ReportRoots)) {
if ($report.Result -eq 'Failed') { throw "Get Help worker reported failure: $($report.Detail) Report: $($report.Path). Installation stopped. Its console may now be waiting at the final keypress prompt; that process lifetime is not ongoing cleanup." }
}
if ($watch.Checked) { continue } if ($watch.Checked) { continue }
if (!$watch.Process.HasExited) { $liveHandles++; continue } if (!$watch.Process.HasExited) { $liveHandles++; continue }
$exitCode = $watch.Process.ExitCode $exitCode = $watch.Process.ExitCode
@@ -1026,19 +1059,13 @@ function Wait-OfficeScrubRemoval {
$null = Write-Output "Scrub worker PID $($watch.Id) exited $exitCode. Removal still requires independent verification." $null = Write-Output "Scrub worker PID $($watch.Id) exited $exitCode. Removal still requires independent verification."
} }
$remaining = @(Get-OfficeSuiteInventory) $remaining = @(Get-OfficeSuiteInventory)
$fresh = $false $status = "Office registrations remaining: $($remaining.Count) [$(($remaining.DisplayName | Sort-Object) -join '; ')]; workers: $(($workers | ForEach-Object { "$($_.Name) PID $($_.ProcessId)" } | Sort-Object) -join '; '); live monitored workers: $liveHandles; observed scrub worker: $observedWorker"
# Avoid racing registry teardown while a known cleanup worker is active.
if (!$workers.Count -and !$liveHandles) {
$state = Get-OfficeClickToRunState
$fresh = !$state.SourceReferences.Count -and !$state.WorkingConfiguration.Count
}
$status = "Office: $(($remaining.DisplayName | Sort-Object) -join '; '); workers: $(($workers | ForEach-Object { "$($_.Name) PID $($_.ProcessId)" } | Sort-Object) -join '; '); live monitored workers: $liveHandles; previous deployment state cleared: $fresh; observed scrub worker: $observedWorker"
if ($status -ne $lastState -or $attempt % 6 -eq 0) { $null = Write-Output $status; $lastState = $status } if ($status -ne $lastState -or $attempt % 6 -eq 0) { $null = Write-Output $status; $lastState = $status }
if ($observedWorker -and !$remaining.Count -and !$workers.Count -and !$liveHandles -and $fresh) { $quietChecks++ } else { $quietChecks = 0 } if ($observedWorker -and !$remaining.Count -and !$workers.Count -and !$liveHandles) { $quietChecks++ } else { $quietChecks = 0 }
if ($quietChecks -ge $definitions.ScrubBackgroundQuietChecks) { return } if ($quietChecks -ge $definitions.ScrubBackgroundQuietChecks) { return }
if ($attempt -lt $definitions.ScrubBackgroundCheckAttempts) { Start-Sleep -Seconds $definitions.ScrubBackgroundCheckSeconds } if ($attempt -lt $definitions.ScrubBackgroundCheckAttempts) { Start-Sleep -Seconds $definitions.ScrubBackgroundCheckSeconds }
} }
throw "Get Help background removal did not finish verification within the allowed time. $status. Installation stopped. Finish any completed keypress prompt; inspect scrub logs if removal failed or no worker was observed." throw "Get Help background removal did not finish verification within the allowed time. $status. Installation has not started and this deployment will not resume automatically. A live worker alone cannot distinguish active removal from the final keypress prompt, which Microsoft displays after success OR failure. Inspect its final console output or diagnostic report before dismissing a completed prompt."
} finally { } finally {
foreach ($watch in $handles.Values) { $watch.Process.Dispose() } foreach ($watch in $handles.Values) { $watch.Process.Dispose() }
} }
@@ -1075,7 +1102,7 @@ function Invoke-OfficeScrubRecovery {
if (!$idle) { throw 'Office scrub processes are still running. Installation stopped to avoid concurrent removal and installation.' } if (!$idle) { throw 'Office scrub processes are still running. Installation stopped to avoid concurrent removal and installation.' }
$removed = Wait-OfficeResult { @(Get-OfficeSuiteInventory).Count -eq 0 } 'all Office registrations to disappear after Get Help scrub' $removed = Wait-OfficeResult { @(Get-OfficeSuiteInventory).Count -eq 0 } 'all Office registrations to disappear after Get Help scrub'
if (!$removed) { throw "Office remains after Get Help scrub: $((Get-OfficeSuiteInventory).DisplayName -join '; '). Installation stopped." } if (!$removed) { throw "Office remains after Get Help scrub: $((Get-OfficeSuiteInventory).DisplayName -join '; '). Installation stopped." }
Assert-OfficeFreshInstallState Assert-OfficeRemovalComplete $Workspace
$null = Write-Output 'Office scrub recovery verified. Reporting restart required; DeferReboot controls whether installation can finish before that restart.' $null = Write-Output 'Office scrub recovery verified. Reporting restart required; DeferReboot controls whether installation can finish before that restart.'
return 3010 return 3010
} }
@@ -1083,17 +1110,16 @@ function Invoke-OfficeScrubRecovery {
function Remove-OfficeSuite { function Remove-OfficeSuite {
param($Media, [string]$Workspace) param($Media, [string]$Workspace)
# ODT is the normal path. A single Get Help scrub is reserved for evidence of # ODT is the normal path. A single Get Help scrub is reserved for evidence of
# broken removal or residual state, before replacement installation begins. # broken product removal, before replacement installation begins.
$existing = @(Get-OfficeSuiteInventory) $existing = @(Get-OfficeSuiteInventory)
$msi = @($existing | Where-Object { $_.WindowsInstaller -eq 1 }) $msi = @($existing | Where-Object { $_.WindowsInstaller -eq 1 })
if ($msi.Count) { $null = Write-Output "MSI Office will be removed by ODT RemoveMSI before it installs the replacement suite: $($msi.DisplayName -join '; ')." } if ($msi.Count) { $null = Write-Output "MSI Office will be removed by ODT RemoveMSI before it installs the replacement suite: $($msi.DisplayName -join '; ')." }
$state = Get-OfficeClickToRunState if (!@($existing | Where-Object { $_.WindowsInstaller -ne 1 }).Count) {
if (!@($existing | Where-Object { $_.WindowsInstaller -ne 1 }).Count -and !$state.Present) { $null = Write-Output 'No registered Click-to-Run products detected; skipping ODT removal and scrub. A remaining ClickToRunSvc or servicing key is not an installed Office product. MSI products remain assigned to RemoveMSI during installation.'
$null = Write-Output 'No Click-to-Run products, service or servicing state detected; skipping the separate ODT removal pass.'
return 0 return 0
} }
if (!$Media.RemovalConfig -or !(Test-Path -LiteralPath $Media.RemovalConfig -PathType Leaf)) { throw 'The staged silent Office removal configuration is missing.' } if (!$Media.RemovalConfig -or !(Test-Path -LiteralPath $Media.RemovalConfig -PathType Leaf)) { throw 'The staged silent Office removal configuration is missing.' }
$null = Write-Output 'Silently removing Click-to-Run Office, including incomplete deployments, Visio and Project, with ODT.' $null = Write-Output "Silently removing registered Click-to-Run products with ODT: $(($existing | Where-Object { $_.WindowsInstaller -ne 1 }).DisplayName -join '; ')."
$startedUtc = [DateTime]::UtcNow $startedUtc = [DateTime]::UtcNow
$code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.RemovalConfig)`"" (Join-Path $Workspace 'office-remove') $code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.RemovalConfig)`"" (Join-Path $Workspace 'office-remove')
if ($code -notin @(0, 3010)) { if ($code -notin @(0, 3010)) {
@@ -1101,6 +1127,12 @@ function Remove-OfficeSuite {
$evidence = Get-OfficeRemovalCorruptionEvidence -SinceUtc $startedUtc $evidence = Get-OfficeRemovalCorruptionEvidence -SinceUtc $startedUtc
if ($evidence) { if ($evidence) {
$null = Write-Output "Office scrub trigger evidence: $($evidence.Path) : $($evidence.Detail)" $null = Write-Output "Office scrub trigger evidence: $($evidence.Path) : $($evidence.Detail)"
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 })
if (!$remaining.Count) {
Assert-OfficeRemovalComplete $Workspace
$null = Write-Output "ODT removal exited $code, but no Click-to-Run products or active workers remain. Skipping a scrub with no product to remove; reporting restart required before continuing according to DeferReboot."
return 3010
}
return Invoke-OfficeScrubRecovery $Media $Workspace "ODT removal exit $code with a current REMOVEINSTALLATION InvalidDirectory error." return Invoke-OfficeScrubRecovery $Media $Workspace "ODT removal exit $code with a current REMOVEINSTALLATION InvalidDirectory error."
} }
} }
@@ -1112,7 +1144,6 @@ function Remove-OfficeSuite {
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 }) $remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 })
return Invoke-OfficeScrubRecovery $Media $Workspace "Office remains after successful ODT removal: $($remaining.DisplayName -join '; ')." return Invoke-OfficeScrubRecovery $Media $Workspace "Office remains after successful ODT removal: $($remaining.DisplayName -join '; ')."
} }
if (!(Test-OfficeFreshInstallState)) { return Invoke-OfficeScrubRecovery $Media $Workspace 'Previous Click-to-Run working configuration or deployment source references remain after successful ODT removal.' }
return 0 return 0
} }
@@ -1440,7 +1471,7 @@ function Invoke-OfficeDeployment {
UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams; OfficeRemovalMethod='SilentODT'; DeferReboot=$Options.DeferReboot UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams; OfficeRemovalMethod='SilentODT'; DeferReboot=$Options.DeferReboot
Workspace=$null; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps; MediaDownloaded=$false Workspace=$null; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps; MediaDownloaded=$false
WritablePaths=$writablePaths; DownloadChecks=$downloadChecks; ClickToRunState=$state; OfficeFeatureRelease=$Options.OfficeFeatureRelease; MetadataResolved=$false WritablePaths=$writablePaths; DownloadChecks=$downloadChecks; ClickToRunState=$state; OfficeFeatureRelease=$Options.OfficeFeatureRelease; MetadataResolved=$false
ScrubRecoveryPolicy='One Get Help scrub for confirmed removal corruption or residual state after successful ODT removal; deployment only.' ScrubRecoveryPolicy='One Get Help scrub for failed removal with registered Click-to-Run products remaining; deployment only. Servicing metadata alone does not trigger removal.'
NextStep='Set ValidateBeforeChanges=false to download, verify, deploy, and clean up installation media. Prerequisites are checked again.' NextStep='Set ValidateBeforeChanges=false to download, verify, deploy, and clean up installation media. Prerequisites are checked again.'
} }
} }
@@ -1466,7 +1497,7 @@ function Invoke-OfficeDeployment {
$receipt = [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @(); ArtifactCleanupPending=$false; ScrubRecoveryAttempted=[bool]$media.ScrubAttempted; ScrubRecoveryReason=$media.ScrubReason } $receipt = [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @(); ArtifactCleanupPending=$false; ScrubRecoveryAttempted=[bool]$media.ScrubAttempted; ScrubRecoveryReason=$media.ScrubReason }
return $receipt return $receipt
} }
Assert-OfficeFreshInstallState Assert-OfficeRemovalComplete $workspace
foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile } foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile }
$userWorkspace = $workspace $userWorkspace = $workspace
if ($profiles.Count) { $userWorkspace = New-OfficeUserWorkspace $media $workspace } if ($profiles.Count) { $userWorkspace = New-OfficeUserWorkspace $media $workspace }
+17 -6
View File
@@ -97,26 +97,29 @@ A window that offers **Get Microsoft Teams (work or school)** does not by itself
Shutdown detection includes `Teams.exe`, `msteams.exe` (older personal/Windows Chat), and `ms-teams.exe`: `Abort` reports these running apps, while an actual deployment with `Force` closes them before removal. Earlier script versions omitted `msteams.exe`; this omission can leave that older process running, but does not explain a window confirmed to be running from `MSTeams\ms-teams.exe`. A sign-out/sign-in or restart can finish session/app registration changes; it is not a guaranteed fix for an unexplained sign-in screen. Shutdown detection includes `Teams.exe`, `msteams.exe` (older personal/Windows Chat), and `ms-teams.exe`: `Abort` reports these running apps, while an actual deployment with `Force` closes them before removal. Earlier script versions omitted `msteams.exe`; this omission can leave that older process running, but does not explain a window confirmed to be running from `MSTeams\ms-teams.exe`. A sign-out/sign-in or restart can finish session/app registration changes; it is not a guaranteed fix for an unexplained sign-in screen.
Removal starts with the separate targeted Appx/provisioned-package and Teams/OneDrive uninstall operations. ODT then runs `setup.exe /configure remove.xml` with `<Remove All="TRUE" />` and `<Display Level="None" AcceptEULA="TRUE" />` to remove Click-to-Run Office, Visio, and Project without installation UI. The XML honors `OfficeAppShutdown`; `Abort` does not silently become `Force`. The script waits for setup to exit and verifies that non-MSI Office registrations disappear, allowing up to five minutes for registration changes. It also runs this pass when a Click-to-Run service or registry state remains without a finished product registration, as happens after an interrupted installation. Only a host with no non-MSI Office registration and no Click-to-Run service/state skips it. 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 installation, a read-only registry check waits for previous Click-to-Run working-configuration markers and references to Emberkom staging paths to disappear. Residual state after ODT reports success can select the single scrub recovery described below. Unreadable state stops the deployment. Deleting staging files or rebooting alone does not prove that Click-to-Run forgot an unfinished deployment. The script does not delete Microsoft's servicing registry or cache itself to force this check to pass; the guard is evidence of known stale state, not a guarantee about every internal Office cache. Before replacement, `Assert-OfficeRemovalComplete` requires no active installer/removal workers and no registered Click-to-Run products. It logs remaining source references and working-configuration markers as diagnostics. It no longer requires Microsoft's internal registry metadata to disappear: successful local-media installations can retain source paths, and metadata alone does not prove an operation is active. Unreadable process/product/registry state still stops deployment. Fresh media is enforced by clearing prior run downloads, creating a unique workspace, and generating this run's SourcePath; the script never deletes Microsoft's internal servicing registry/cache to force a check to pass.
Legacy MSI Office is handled by `<RemoveMSI />` in `install.xml`: ODT removes those products before installing the replacement suite in the same operation. Microsoft's [RemoveMSI guidance](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/upgrade-from-msi-version) covers Office, Visio, and Project 2007/2010/2013/2016. The script does not assume that a standalone `RemoveMSI` configuration without an installation is supported. Consequently, MSI Office can still be present during our identity/user-cleanup phase. After ODT finishes installation, the script verifies that detected MSI Office registrations are gone and the requested new product/version is installed. A completed MSI migration reports `3010` because a restart is required to finish removal, even if ODT returns zero. Legacy MSI Office is handled by `<RemoveMSI />` in `install.xml`: ODT removes those products before installing the replacement suite in the same operation. Microsoft's [RemoveMSI guidance](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/upgrade-from-msi-version) covers Office, Visio, and Project 2007/2010/2013/2016. The script does not assume that a standalone `RemoveMSI` configuration without an installation is supported. Consequently, MSI Office can still be present during our identity/user-cleanup phase. After ODT finishes installation, the script verifies that detected MSI Office registrations are gone and the requested new product/version is installed. A completed MSI migration reports `3010` because a restart is required to finish removal, even if ODT returns zero.
Automatic recovery is limited to **one Get Help Office scrub per deployment**, before replacement installation begins. It is selected only for these conditions: Automatic recovery is limited to **one Get Help Office scrub per deployment**, before replacement installation begins. It is selected only for these conditions:
- ODT removal exits `17002` or `17004`, and a native log entry timestamped during that attempt identifies `InvalidDirectory` in `REMOVEINSTALLATION` (including the observed missing `root\integration` error). Historical entries, generic exit-code wrappers and download failures do not qualify. - 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. - ODT exits zero, but non-MSI Office registrations remain after the bounded verification wait.
- ODT exits zero and product removal is verified, but previous Click-to-Run working configuration or deployment source references remain after their 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. 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 previous Click-to-Run working/source state to clear. 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. 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 previous deployment state, and requires all conditions to stay clear for the quiet interval. Failed/interrupted workers, inaccessible exit status, no observed worker, remaining products/state or a timeout stop installation. The overall Syncro limit still applies. 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. **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). 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. 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.
@@ -134,6 +137,14 @@ Transient failures get bounded recovery before deployment stops:
Retries and waits are recorded in the diagnostic log. Persistent failures still stop the run with an error; these recovery paths do not turn incomplete deployment into success. Retry counts and delays are grouped in `Get-OfficeDeploymentDefinitions`; the standalone user helper has its MSI retry settings in `Get-OfficeUserCleanupDefinitions`. Retries and waits are recorded in the diagnostic log. Persistent failures still stop the run with an error; these recovery paths do not turn incomplete deployment into success. Retry counts and delays are grouped in `Get-OfficeDeploymentDefinitions`; the standalone user helper has its MSI retry settings in `Get-OfficeUserCleanupDefinitions`.
## Investigating a failed deployment without rerunning it
`Get-OfficeDeploymentDiagnostics.ps1` collects evidence without importing or executing the installer. Copy this root script to the endpoint and run it in elevated PowerShell, or publish it and use `rmm/Get-OfficeDeploymentDiagnostics.ps1` as SYSTEM. The RMM caller fetches Tools and the core live and needs no inputs. It writes a ZIP under `C:\ProgramData\Emberkom\Logs\OfficeDiagnostics` and prints the full path. No deployment folder, payload download, uninstall, repair, process termination, registry write, or task registration is performed by the collector. The normal RMM Tools bootstrap still initializes its management logs.
The ZIP includes the last 72 hours of native Office logs from Windows and user temp folders, Office-related management logs, deployment logs/configuration XML, and Get Help DAF reports across all discovered profiles. It includes the GetHelpElevated launcher/support scripts for inspection, even when their package timestamps are older. Current boot time, process owners/sessions, Click-to-Run service state, selected Office registry values from both views, installed Office entries, and Emberkom cleanup tasks are captured separately in `endpoint.json`. It excludes installation executables and media, user documents, and identity/licensing-store exports. Logs can contain user names and paths. `manifest.json` records original paths/timestamps; `collection-issues.json` records access failures and collection limits (64 MB/file, 512 MB total, 2000 files). Live files are copied with shared access and are not an atomic snapshot.
Compare timestamps inside the native logs for the failed `REMOVEINSTALLATION` and successful installation operations. Running the same staged `setup.exe /configure install.xml` successfully establishes that this media/configuration can install in the later endpoint state and execution context. It does not prove removal completed at the earlier timeout, nor establish behavior under SYSTEM. A reboot after a scrub and a reboot before a deployment that launches another scrub are different sequences. Current registry/service/process state cannot reconstruct the earlier state by itself. Preserve a now-working installation while collecting this evidence; use a disposable VM with a restored baseline for destructive comparisons.
## Identity cleanup and absent users ## Identity cleanup and absent users
The core script clears Office 15/16 identity/licensing registry keys and Office licensing token folders in each locally available non-special Windows profile, loading unloaded user hives when needed. Unavailable profiles/containers stop deployment before removal. FSLogix/roaming profiles that are not registered locally are outside this script's coverage. The core script clears Office 15/16 identity/licensing registry keys and Office licensing token folders in each locally available non-special Windows profile, loading unloaded user hives when needed. Unavailable profiles/containers stop deployment before removal. FSLogix/roaming profiles that are not registered locally are outside this script's coverage.
+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
@@ -6,7 +6,8 @@
# [string]$ValidateBeforeChanges - true (default: validate only), false (remove/reinstall) # [string]$ValidateBeforeChanges - true (default: validate only), false (remove/reinstall)
# Assessment checks writable paths and HTTP HEAD 200; it creates no deployment directory or downloads. # 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. # Deployment clears prior run artifacts, downloads fresh media before uninstalling, and leaves only logs.
# Confirmed ODT removal corruption or residual state can trigger one Microsoft Get Help scrub. # 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. # 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. # 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. # Leave its window open during removal; dismiss a completed 'Press any key to exit' prompt.
@@ -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
}
+87 -18
View File
@@ -549,12 +549,13 @@ try {
[pscustomobject]@{DisplayName='Microsoft Office Professional Plus 2016'; WindowsInstaller=1} [pscustomobject]@{DisplayName='Microsoft Office Professional Plus 2016'; WindowsInstaller=1}
if ($script:removalMode -eq 'msi-only') { return } if ($script:removalMode -eq 'msi-only') { return }
if ($script:removalStarted -and $script:removalMode -eq 'read-error') { throw 'Office inventory is unreadable' } if ($script:removalStarted -and $script:removalMode -eq 'read-error') { throw 'Office inventory is unreadable' }
if (!$script:removalStarted -or $script:removalMode -eq 'remaining' -or ($script:removalMode -eq 'delayed' -and $script:removalChecks -le 3)) { if (!$script:removalStarted -or $script:removalMode -in @('remaining','corrupt') -or ($script:removalMode -eq 'delayed' -and $script:removalChecks -le 3)) {
[pscustomobject]@{DisplayName='Microsoft Office Home and Business 2021 - en-us'} [pscustomobject]@{DisplayName='Microsoft Office Home and Business 2021 - en-us'}
} }
} }
function Get-OfficeClickToRunState { [pscustomobject]@{Present=($script:removalMode -eq 'orphan');SourceReferences=@();WorkingConfiguration=@($(if ($script:removalMode -eq 'stale') {'old-guid'}))} } function Get-OfficeClickToRunState { [pscustomobject]@{Present=($script:removalMode -eq 'orphan');SourceReferences=@();WorkingConfiguration=@($(if ($script:removalMode -eq 'stale') {'old-guid'}))} }
function Get-OfficeRemovalCorruptionEvidence { if ($script:removalMode -eq 'corrupt') { [pscustomobject]@{Path='fixture.log';Detail='REMOVEINSTALLATION InvalidDirectory'} } } 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-OfficeScrubRecovery { param($Media,$Workspace,$Reason) $script:scrubCalls++; Assert-OfficeTest (![string]::IsNullOrWhiteSpace($Reason)) 'Recovery must record its reason.'; return 3010 }
function Invoke-OfficeProcess { function Invoke-OfficeProcess {
param($FilePath,$Arguments,$LogPrefix) param($FilePath,$Arguments,$LogPrefix)
@@ -566,9 +567,9 @@ try {
$removalPath = Join-Path $testRoot 'remove [literal].xml' $removalPath = Join-Path $testRoot 'remove [literal].xml'
(New-OfficeRemovalConfiguration ([pscustomobject]@{OfficeAppShutdown='Force'})).Save($removalPath) (New-OfficeRemovalConfiguration ([pscustomobject]@{OfficeAppShutdown='Force'})).Save($removalPath)
$media = [pscustomobject]@{Setup='inert-setup.exe'; RemovalConfig=$removalPath} $media = [pscustomobject]@{Setup='inert-setup.exe'; RemovalConfig=$removalPath}
foreach ($script:removalMode in @('empty','orphan','msi-only','mixed','delayed','remaining','stale','corrupt','unknown-17004','read-error','fatal','reboot')) { foreach ($script:removalMode in @('empty','orphan','msi-only','mixed','delayed','remaining','stale','corrupt','corrupt-gone','unknown-17004','read-error','fatal','reboot')) {
$script:removalChecks=0; $script:removalCalls=0; $script:removalStarted=$false; $script:scrubCalls=0 $script:removalChecks=0; $script:removalCalls=0; $script:removalStarted=$false; $script:scrubCalls=0
$script:removalCode = switch ($script:removalMode) { 'fatal' {1603}; 'reboot' {3010}; 'corrupt' {17004}; 'unknown-17004' {17004}; default {0} } $script:removalCode = switch ($script:removalMode) { 'fatal' {1603}; 'reboot' {3010}; 'corrupt' {17004}; 'corrupt-gone' {17004}; 'unknown-17004' {17004}; default {0} }
if ($script:removalMode -eq 'remaining') { if ($script:removalMode -eq 'remaining') {
Assert-OfficeTest ((Remove-OfficeSuite $media $testRoot) -eq 3010) 'Verified leftovers after ODT success must select scrub recovery.' Assert-OfficeTest ((Remove-OfficeSuite $media $testRoot) -eq 3010) 'Verified leftovers after ODT success must select scrub recovery.'
Assert-OfficeTest ($script:removalChecks -eq ((Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts + 2)) 'Remaining Click-to-Run products must be checked for the bounded registration interval.' Assert-OfficeTest ($script:removalChecks -eq ((Get-OfficeDeploymentDefinitions).RegistrationCheckAttempts + 2)) 'Remaining Click-to-Run products must be checked for the bounded registration interval.'
@@ -578,14 +579,14 @@ try {
Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'ODT Office removal failed.*automatic scrub was not selected' Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'ODT Office removal failed.*automatic scrub was not selected'
} else { } else {
$result = @(Remove-OfficeSuite $media $testRoot) $result = @(Remove-OfficeSuite $media $testRoot)
$expected = if ($script:removalMode -in @('reboot','corrupt','stale')) {3010} else {0} $expected = if ($script:removalMode -in @('reboot','corrupt','corrupt-gone')) {3010} else {0}
Assert-OfficeTest ($result.Count -eq 1 -and $result[0] -eq $expected) 'Removal must return just its exit code; MSI products are deferred to installation.' Assert-OfficeTest ($result.Count -eq 1 -and $result[0] -eq $expected) 'Removal must return just its exit code; MSI products are deferred to installation.'
if ($script:removalMode -eq 'delayed') { Assert-OfficeTest ($script:removalChecks -eq 4) 'Removal must tolerate registry propagation delays.' } if ($script:removalMode -eq 'delayed') { Assert-OfficeTest ($script:removalChecks -eq 4) 'Removal must tolerate registry propagation delays.' }
if ($script:removalMode -eq 'reboot') { Assert-OfficeTest ($script:removalChecks -eq 1) 'A required restart must be surfaced before demanding registration cleanup.' } if ($script:removalMode -eq 'reboot') { Assert-OfficeTest ($script:removalChecks -eq 1) 'A required restart must be surfaced before demanding registration cleanup.' }
} }
$expectedCalls = if ($script:removalMode -in @('empty','msi-only')) {0} else {1} $expectedCalls = if ($script:removalMode -in @('empty','orphan','msi-only')) {0} else {1}
Assert-OfficeTest ($script:removalCalls -eq $expectedCalls) 'Remove orphaned Click-to-Run state even without registered products, without rerunning ODT.' 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','stale')) {1} else {0})) 'Only confirmed removal corruption or leftovers may trigger a single scrub.' 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.'
} }
} }
& { & {
@@ -953,11 +954,41 @@ try {
Assert-OfficeThrows { Open-OfficeScrubWorkerHandle ([pscustomobject]@{ProcessId=$PID;CreationDate=[datetime]'2000-01-01'}) } 'Process identity changed' Assert-OfficeThrows { Open-OfficeScrubWorkerHandle ([pscustomobject]@{ProcessId=$PID;CreationDate=[datetime]'2000-01-01'}) } 'Process identity changed'
} finally { if ($held) { $held.Dispose() }; $probe.Dispose() } } 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 # 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. # 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'} $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'} $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 { function Get-OfficeScrubWorkers {
$script:waitPoll++ $script:waitPoll++
if ($script:waitMode -eq 'process-error') { throw 'Process inventory unreadable' } if ($script:waitMode -eq 'process-error') { throw 'Process inventory unreadable' }
@@ -979,22 +1010,28 @@ try {
if ($script:waitMode -eq 'remaining' -or ($script:waitMode -eq 'delayed' -and $script:waitPoll -le 4)) { [pscustomobject]@{DisplayName='Old Office'} } if ($script:waitMode -eq 'remaining' -or ($script:waitMode -eq 'delayed' -and $script:waitPoll -le 4)) { [pscustomobject]@{DisplayName='Old Office'} }
} }
function Get-OfficeClickToRunState { function Get-OfficeClickToRunState {
$script:waitStateReads++
if ($script:waitMode -eq 'state-error') { throw 'Servicing state unreadable' } if ($script:waitMode -eq 'state-error') { throw 'Servicing state unreadable' }
[pscustomobject]@{SourceReferences=@($(if ($script:waitMode -eq 'stale') {'old-download'}));WorkingConfiguration=@()} [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','state-error','lost-handle')) { 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:waitPoll=0; $script:disposed=0; $script:openCalls=0; $script:testSleeps=@(); $script:waitStateReads=0
if ($script:waitMode -in @('success','restart','delayed','quiet-reset')) { if ($script:waitMode -in @('success','restart','delayed','quiet-reset','stale')) {
$result=@(Wait-OfficeScrubRemoval @($existing)) $result=@(Wait-OfficeScrubRemoval @($existing))
$expectedPolls=switch ($script:waitMode) { 'delayed' {11}; 'quiet-reset' {12}; default {9} } $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.' 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 { } 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'} } $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 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.' } 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: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: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 # A scrub requires both a successful scenario/process result and independently
@@ -1036,7 +1073,7 @@ try {
if ($script:scrubMode -eq 'remaining') { [pscustomobject]@{DisplayName='Leftover MSI Office';WindowsInstaller=1} } if ($script:scrubMode -eq 'remaining') { [pscustomobject]@{DisplayName='Leftover MSI Office';WindowsInstaller=1} }
if ($script:scrubMode -eq 'inventory-error') { throw 'Registry unreadable' } if ($script:scrubMode -eq 'inventory-error') { throw 'Registry unreadable' }
} }
function Assert-OfficeFreshInstallState { if ($script:scrubMode -eq 'stale') { throw 'Previous Click-to-Run state remains' } } 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')) { 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) $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 $media=[pscustomobject]@{}; $script:scrubExit=0; $script:scrubOutput='00: Successfully completed this scenario.'; $script:backgroundWaits=0; $script:usageCalls=0
@@ -1060,7 +1097,7 @@ try {
$result=@(Invoke-OfficeScrubRecovery $media $workspace 'fixture corruption') $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.' 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 { } 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' {'Click-to-Run state remains'}; default {'failed or returned an unverified result'} } $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-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:usageCalls -eq $(if ($script:scrubMode -eq 'download') {0} else {1})) 'Probe the fresh scrubber usage exactly once, only after recovery was selected.'
@@ -1147,6 +1184,29 @@ try {
$file = Join-Path $testRoot 'not-a-directory'; Set-Content -LiteralPath $file -Value 'fixture' $file = Join-Path $testRoot 'not-a-directory'; Set-Content -LiteralPath $file -Value 'fixture'
Assert-OfficeThrows { Assert-OfficeWritablePath $file } 'not a directory' 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. # Inspect persisted state without touching the actual registry or Office service.
& { & {
function Test-Path { return $true } function Test-Path { return $true }
@@ -1156,11 +1216,20 @@ try {
function Get-ItemProperty { [pscustomobject]@{WorkingConfiguration='old-guid';SourcePath='C:\Windows\SystemTemp\EmberkomOfficeDeployment\old\ODT';Platform='x64'} } function Get-ItemProperty { [pscustomobject]@{WorkingConfiguration='old-guid';SourcePath='C:\Windows\SystemTemp\EmberkomOfficeDeployment\old\ODT';Platform='x64'} }
$state = Get-OfficeClickToRunState $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.' 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.'
Assert-OfficeThrows { Assert-OfficeFreshInstallState } 'still retains previous deployment state.*Installation stopped.*old-guid' 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'} } function Get-ItemProperty { [pscustomobject]@{Platform='x64'} }
$null = Assert-OfficeFreshInstallState $null = Assert-OfficeRemovalComplete
function Get-ItemProperty { throw 'Registry access denied' } function Get-ItemProperty { throw 'Registry access denied' }
Assert-OfficeThrows { Assert-OfficeFreshInstallState } 'Registry access denied' Assert-OfficeThrows { Assert-OfficeRemovalComplete } 'Registry access denied'
} }
# Execute the real deferred action with only its live download replaced. # Execute the real deferred action with only its live download replaced.
& { & {
@@ -1279,7 +1348,7 @@ try {
function Test-OfficeDownloadLinks { [pscustomobject]@{StatusCode=200;Method='HEAD'} } function Test-OfficeDownloadLinks { [pscustomobject]@{StatusCode=200;Method='HEAD'} }
function Get-OfficeClickToRunState { [pscustomobject]@{Present=$false;SourceReferences=@();WorkingConfiguration=@()} } 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 Clear-OfficePreviousDeploymentFiles { if ($script:mode -eq 'old-cache') { throw 'Previous artifacts are locked' }; $script:priorCleanupRuns++ }
function Assert-OfficeFreshInstallState { if ($script:mode -eq 'stale-state') { throw 'Previous Click-to-Run state remains' } } 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 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 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 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 ,@() }
@@ -1317,7 +1386,7 @@ try {
function Install-OfficeCompanionApps { param($Media,$Workspace,[bool]$InstallTeams) $script:teamsRequested=$InstallTeams; $script:events += 'install-companions'; if ($script:mode -eq 'install-companions') { throw 'companion install failure' }; [pscustomobject]@{ExitCode=$(if ($script:mode -eq 'companion-reboot') {3010} else {0}); Versions=@{NewOutlook='1'; OneDrive='1'}} } function Install-OfficeCompanionApps { param($Media,$Workspace,[bool]$InstallTeams) $script:teamsRequested=$InstallTeams; $script:events += 'install-companions'; if ($script:mode -eq 'install-companions') { throw 'companion install failure' }; [pscustomobject]@{ExitCode=$(if ($script:mode -eq 'companion-reboot') {3010} else {0}); Versions=@{NewOutlook='1'; OneDrive='1'}} }
$script:removalStillRegistered=$false $script:removalStillRegistered=$false
$options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'; DeferReboot='false'} $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'; DeferReboot='false'}
foreach ($script:mode in @('success','download','download-cleanup','disk-space','companions','remove-office','stale-state','identity','user','phase','install','install-companions','pending','reboot','office-reboot','companion-reboot')) { foreach ($script:mode in @('success','download','download-cleanup','disk-space','companions','remove-office','readiness-error','identity','user','phase','install','install-companions','pending','reboot','office-reboot','companion-reboot')) {
$script:artifactCleanupRuns = 0 $script:artifactCleanupRuns = 0
$script:events = @(); $errorResult = $null; $result = $null $script:events = @(); $errorResult = $null; $result = $null
try { $result = Invoke-OfficeDeployment $options } catch { $errorResult = $_ } try { $result = Invoke-OfficeDeployment $options } catch { $errorResult = $_ }
+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"
}