fixed an issue with the cli args for the scrubber tool
This commit is contained in:
@@ -33,10 +33,21 @@ function Get-OfficeDeploymentDefinitions {
|
||||
OdtDownloadPattern = 'https://download\.microsoft\.com/[^"\s<>]+/officedeploymenttool_[a-zA-Z0-9_-]+\.exe'
|
||||
GetHelpUrl = 'https://aka.ms/SaRA_EnterpriseVersionFiles'
|
||||
GetHelpExecutable = 'GetHelpCmd.exe'
|
||||
ScrubArguments = '-S OfficeScrubScenario -AcceptEula -OfficeVersion All'
|
||||
ScrubArguments = '-S OfficeScrubScenario -AcceptEula'
|
||||
ScrubAllVersionsArgument = '-OfficeVersion All'
|
||||
ScrubHelpArguments = '-?'
|
||||
ScrubHelpPattern = '(?im)^\s*GetHelpCmd\.exe\s+-S\s+OfficeScrubScenario\s+-AcceptEula(?:\s|$)'
|
||||
ScrubVersionSwitchPattern = '(?im)^\s*-OfficeVersion\b'
|
||||
ScrubScenarioPattern = '(?m)^\s*(\d{2}):'
|
||||
ScrubScenarioSuccess = @('00', '66', '68')
|
||||
ScrubExitSuccess = @(0, 66, 68)
|
||||
ScrubTextSuccessPattern = '(?im)^\s*Scenario completed successfully\.\s*$'
|
||||
ScrubBackgroundPattern = '(?im)^\s*ExecutionResultDetails:\s*Uninstall office is running in the background\.'
|
||||
ScrubFailurePattern = '(?im)^\s*(?:Error\s*:|(?:-\s*)?Uninstall Office Scenario failed\.|The scenario requires an elevated command-prompt\.)'
|
||||
ScrubBackgroundCheckAttempts = 181
|
||||
ScrubBackgroundCheckSeconds = 10
|
||||
ScrubBackgroundQuietChecks = 7
|
||||
ScrubWorkerNames = @('powershell.exe', 'pwsh.exe', 'cscript.exe', 'wscript.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'OfficeClickToRun.exe', 'setup.exe', 'integratedoffice.exe')
|
||||
HelperVersion = 'EmberkomOfficeUserCleanup-v4'
|
||||
Language = 'en-us'
|
||||
OfficeBuildPattern = '^16\.0\.\d+\.\d+$'
|
||||
@@ -285,6 +296,13 @@ function Initialize-OfficeMedia {
|
||||
$scrub = @(Get-ChildItem -LiteralPath $scrubFolder -Filter $definitions.GetHelpExecutable -File -Recurse)
|
||||
if ($scrub.Count -ne 1) { throw "Microsoft download did not contain exactly one $($definitions.GetHelpExecutable)." }
|
||||
Assert-OfficeMicrosoftSignature $scrub[0].FullName
|
||||
# Check the downloaded executable's own syntax before any removal. Current Get Help
|
||||
# rejects the documented -OfficeVersion switch and internally requests All instead.
|
||||
$helpPrefix = Join-Path $Workspace 'gethelp-usage'
|
||||
$helpCode = Invoke-OfficeProcess $scrub[0].FullName $definitions.ScrubHelpArguments $helpPrefix
|
||||
$helpText = (Get-Content -LiteralPath "$helpPrefix.stdout.log" -Raw -ErrorAction Stop) + "`n" + (Get-Content -LiteralPath "$helpPrefix.stderr.log" -Raw -ErrorAction Stop)
|
||||
$scrubArguments = Get-OfficeScrubArguments $helpCode $helpText
|
||||
$null = Write-Output "Validated Get Help command: $scrubArguments. Usage logs: $helpPrefix"
|
||||
# Run-Script only downloads the core file, so stage its helper explicitly.
|
||||
$helper = Join-Path $Workspace 'Office-UserCleanup.ps1'
|
||||
Save-OfficeDownload "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1" $helper
|
||||
@@ -310,7 +328,7 @@ function Initialize-OfficeMedia {
|
||||
}
|
||||
$config.Configuration.Add.SetAttribute('Version', $versions[0].Name); $config.Save($configPath)
|
||||
$companions = Initialize-OfficeCompanionMedia $Workspace -InstallTeams $Options.InstallTeams
|
||||
[pscustomobject]@{ Setup = $setup; Scrubber = $scrub[0].FullName; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions }
|
||||
[pscustomobject]@{ Setup = $setup; Scrubber = $scrub[0].FullName; ScrubArguments = $scrubArguments; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions }
|
||||
}
|
||||
|
||||
function Get-OfficeRunningApps {
|
||||
@@ -446,25 +464,79 @@ function Get-OfficeSuiteInventory {
|
||||
if ($c2r.ProductReleaseIds) { [pscustomobject]@{ DisplayName = "Click-to-Run: $($c2r.ProductReleaseIds)" } }
|
||||
}
|
||||
|
||||
function Get-OfficeScrubArguments {
|
||||
param([int]$ExitCode, [string]$HelpText)
|
||||
$definitions = Get-OfficeDeploymentDefinitions
|
||||
if ($ExitCode -ne 0 -or $HelpText -match $definitions.ScrubFailurePattern -or $HelpText -notmatch $definitions.ScrubHelpPattern) {
|
||||
throw "Could not validate the downloaded Get Help command syntax (exit $ExitCode). No apps have been removed. Check gethelp-usage logs."
|
||||
}
|
||||
if ($HelpText -match $definitions.ScrubVersionSwitchPattern) { return "$($definitions.ScrubArguments) $($definitions.ScrubAllVersionsArgument)" }
|
||||
$definitions.ScrubArguments
|
||||
}
|
||||
|
||||
function Assert-OfficeScrubResult {
|
||||
param([int]$ExitCode, [string]$Output, [object[]]$RemainingOffice)
|
||||
# Microsoft's scenario output is checked separately from the process exit code.
|
||||
$definitions = Get-OfficeDeploymentDefinitions
|
||||
$summary = ($Output -replace '\s+', ' ').Trim()
|
||||
if ($summary.Length -gt 1000) { $summary = $summary.Substring(0, 1000) + '...' }
|
||||
if ($Output -match $definitions.ScrubFailurePattern) { throw "Get Help removal failed (process exit $ExitCode). $summary" }
|
||||
$results = [regex]::Matches($Output, $definitions.ScrubScenarioPattern)
|
||||
if (!$results.Count) { throw "Get Help returned no recognizable scenario result (process exit $ExitCode). Check scrub logs." }
|
||||
$result = $results[$results.Count - 1].Groups[1].Value
|
||||
if ($result -notin $definitions.ScrubScenarioSuccess -or $ExitCode -notin $definitions.ScrubExitSuccess) { throw "Get Help removal failed: scenario $result, process $ExitCode. Check scrub logs." }
|
||||
if ($results.Count) {
|
||||
$failed = @($results | Where-Object { $_.Groups[1].Value -notin $definitions.ScrubScenarioSuccess })
|
||||
if ($failed.Count -or $ExitCode -notin $definitions.ScrubExitSuccess) { throw "Get Help removal failed: scenario $($results[$results.Count - 1].Groups[1].Value), process $ExitCode. $summary" }
|
||||
} elseif ($Output -notmatch $definitions.ScrubTextSuccessPattern -or $ExitCode -ne 0) {
|
||||
throw "Get Help returned no recognizable successful scenario result (process exit $ExitCode). Output: $summary. Check scrub logs."
|
||||
}
|
||||
if (@($RemainingOffice).Count) { throw "Office remains after cleanup: $(($RemainingOffice | ForEach-Object { $_.DisplayName }) -join '; '). Reboot/repair and rerun; installation stopped." }
|
||||
}
|
||||
|
||||
function Get-OfficeScrubWorkers {
|
||||
$definitions = Get-OfficeDeploymentDefinitions
|
||||
$filter = ($definitions.ScrubWorkerNames | ForEach-Object { "Name='$_'" }) -join ' OR '
|
||||
Get-CimInstance Win32_Process -Filter $filter -ErrorAction Stop | Where-Object {
|
||||
# Idle service hosts can outlive an uninstall. Track clients and script workers.
|
||||
$_.ProcessId -ne $PID -and
|
||||
!($_.Name -eq 'msiexec.exe' -and $_.CommandLine -match '(?i)\s/(V|Embedding)\b') -and
|
||||
!($_.Name -eq 'OfficeClickToRun.exe' -and $_.CommandLine -match '(?i)\s/service\b')
|
||||
}
|
||||
}
|
||||
|
||||
function Wait-OfficeScrubRemoval {
|
||||
param([object[]]$ExistingWorkers)
|
||||
$definitions = Get-OfficeDeploymentDefinitions
|
||||
$baseline = @{}
|
||||
foreach ($worker in $ExistingWorkers) { $baseline["$($worker.ProcessId)|$($worker.CreationDate)"] = $true }
|
||||
$quietChecks = 0; $lastState = $null
|
||||
$null = Write-Output "Get Help started background removal. Waiting up to $([int](($definitions.ScrubBackgroundCheckAttempts - 1) * $definitions.ScrubBackgroundCheckSeconds / 60)) minutes for Office removal and cleanup workers to finish."
|
||||
for ($attempt = 1; $attempt -le $definitions.ScrubBackgroundCheckAttempts; $attempt++) {
|
||||
$remaining = @(Get-OfficeSuiteInventory)
|
||||
$workers = @(Get-OfficeScrubWorkers | Where-Object {
|
||||
!$baseline.ContainsKey("$($_.ProcessId)|$($_.CreationDate)") -or $_.CommandLine -match '(?i)(OffScrub|OfficeScrub|OfficeUninstall)'
|
||||
})
|
||||
$state = "Office: $(($remaining.DisplayName | Sort-Object) -join '; '); cleanup workers: $(($workers | ForEach-Object { "$($_.Name) PID $($_.ProcessId)" } | Sort-Object) -join '; ')"
|
||||
if ($state -ne $lastState) { $null = Write-Output $state; $lastState = $state }
|
||||
if (!$remaining.Count -and !$workers.Count) { $quietChecks++ } else { $quietChecks = 0 }
|
||||
# A launch acknowledgement is not completion. Require a quiet interval as well
|
||||
# as empty inventory to avoid starting ODT while a detected detached worker is active.
|
||||
if ($quietChecks -ge $definitions.ScrubBackgroundQuietChecks) { return }
|
||||
if ($attempt -lt $definitions.ScrubBackgroundCheckAttempts) { Start-Sleep -Seconds $definitions.ScrubBackgroundCheckSeconds }
|
||||
}
|
||||
throw "Get Help background removal did not finish within the allowed time. $state. Installation stopped. Check scrub logs and restart before rerunning if cleanup is still active."
|
||||
}
|
||||
|
||||
function Remove-OfficeSuite {
|
||||
param($Media, [string]$Workspace)
|
||||
$null = Write-Output 'Removing Office, including Visio and Project, with Microsoft Get Help.'
|
||||
$prefix = Join-Path $Workspace 'office-scrub'
|
||||
$code = Invoke-OfficeProcess $Media.Scrubber (Get-OfficeDeploymentDefinitions).ScrubArguments $prefix
|
||||
$output = (Get-Content -LiteralPath "$prefix.stdout.log" -Raw -ErrorAction Stop) + (Get-Content -LiteralPath "$prefix.stderr.log" -Raw -ErrorAction Stop)
|
||||
if (!$Media.ScrubArguments) { throw 'Get Help command syntax was not validated before removal.' }
|
||||
$existingWorkers = @(Get-OfficeScrubWorkers)
|
||||
$code = Invoke-OfficeProcess $Media.Scrubber $Media.ScrubArguments $prefix
|
||||
$output = (Get-Content -LiteralPath "$prefix.stdout.log" -Raw -ErrorAction Stop) + "`n" + (Get-Content -LiteralPath "$prefix.stderr.log" -Raw -ErrorAction Stop)
|
||||
$null = Write-Output "Get Help output ($prefix):`n$output"
|
||||
Assert-OfficeScrubResult $code $output @()
|
||||
$null = Wait-OfficeResult { @(Get-OfficeSuiteInventory).Count -eq 0 } 'Office removal registration'
|
||||
if ($output -match (Get-OfficeDeploymentDefinitions).ScrubBackgroundPattern) { Wait-OfficeScrubRemoval $existingWorkers }
|
||||
else { $null = Wait-OfficeResult { @(Get-OfficeSuiteInventory).Count -eq 0 } 'Office removal registration' }
|
||||
Assert-OfficeScrubResult $code $output @(Get-OfficeSuiteInventory)
|
||||
}
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ Validation writes logs and staging files, secures its workspace, and runs ODT ex
|
||||
|
||||
The script resolves the current versioned ODT download from the [Microsoft Download Center](https://www.microsoft.com/en-us/download/details.aspx?id=49117). It does not depend on the Emberkom-hosted setup.exe or a frozen Microsoft binary URL. If the page format changes, it stops before removal. The downloaded ODT package and extracted setup.exe must have valid Microsoft signatures.
|
||||
|
||||
The [Get Help command-line package](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-command-line-overview) is downloaded fresh and its executable signature checked. Microsoft's evergreen link still uses the historical name `https://aka.ms/SaRA_EnterpriseVersionFiles`. The script executes `GetHelpCmd.exe`, not retired `SaRAcmd.exe`.
|
||||
The [Get Help command-line package](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-command-line-overview) is downloaded fresh and its executable signature checked. Microsoft's evergreen link still uses the historical name `https://aka.ms/SaRA_EnterpriseVersionFiles`. The script executes `GetHelpCmd.exe`, not retired `SaRAcmd.exe`. During staging (including validation-only runs), it runs only the read-only `-?` usage command to verify the downloaded tool's command syntax; this does not start an uninstall scenario. Usage output is retained in `gethelp-usage.stdout.log` / `.stderr.log`.
|
||||
|
||||
ODT downloads the current build in the selected channel first. Installation is pinned to that local build, uses English (`en-us`), enables updates, and uses `Display Level="None"`. The [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options) describes these settings. Existing update policies can subsequently override the chosen channel.
|
||||
|
||||
@@ -80,13 +80,15 @@ These follow Microsoft's deployment guidance for [Teams](https://learn.microsoft
|
||||
|
||||
New Outlook, and Teams when selected, are provisioned for current and future users; users may need to sign out and back in for registration. OneDrive installs per-machine and handles migration of existing user accounts. App account setup and any tenant policy prompts are separate from the silent installation. The script does not switch the default mail application, force migration from classic Outlook, or configure OneDrive folder backup.
|
||||
|
||||
Removal uses [Get Help's OfficeScrubScenario](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall) with `-OfficeVersion All`, plus separate targeted Appx/provisioned-package and Teams/OneDrive uninstall operations. Office 2007 through Microsoft 365/2024 are covered by the documented scrubber options. Corrupt, unsupported, orphaned, or unusually packaged installations may require manual repair; unknown uninstall commands and remaining detected Office products stop the deployment. This is not a guarantee that every historical Office artifact is erased. No automatic reboot or resume task is created.
|
||||
Removal uses [Get Help's OfficeScrubScenario](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall), plus separate targeted Appx/provisioned-package and Teams/OneDrive uninstall operations. The script adds `-OfficeVersion All` only when the downloaded tool's usage advertises that switch. The Microsoft-signed build inspected on October 14, 2026 (`1.0.0+d28f675`) rejects it despite Microsoft's documentation; that build internally sets `officeVersion=All` when invoked as `GetHelpCmd.exe -S OfficeScrubScenario -AcceptEula`. The documented coverage spans Office 2007 through Microsoft 365/2024, but actual removal still depends on the downloaded tool's implementation and the endpoint's installation state. Corrupt, unsupported, orphaned, or unusually packaged installations may require manual repair; unknown uninstall commands and remaining detected Office products stop the deployment. No automatic reboot or resume task is created.
|
||||
|
||||
The script recognizes both the older numbered scenario results and the current `Scenario completed successfully.` message. A process exit of zero alone does not prove success: this Get Help build also returns zero for invalid arguments. Error text is logged and included in the Syncro failure message. When Get Help reports that uninstall is running in the background, the script polls for up to 30 minutes, requiring Office inventory to become empty and newly launched installer/script workers to exit, followed by a 60-second quiet interval. Existing unrelated consoles and idle installer service hosts do not block completion. This avoids immediately reinstalling after a background-launch acknowledgement. A timeout stops installation and reports remaining products/workers; do not launch another deployment over unfinished cleanup.
|
||||
|
||||
Transient failures get bounded recovery before deployment stops:
|
||||
|
||||
- HTTP downloads, including the ODT discovery page, get three attempts. ODT `/download` also gets three attempts using the same staging folder, before any app removal. An unrecognized discovery page, invalid signature, or invalid staged payload still fails validation.
|
||||
- Machine and per-user MSI removal retry Windows Installer's [busy result, `1618`](https://learn.microsoft.com/en-us/windows/win32/msi/error-codes), up to five attempts with 15 seconds between attempts. Other installer failure codes retain their existing handling. The script does not kill an unrelated installer or blindly repeat an Office installation or scrub.
|
||||
- After successful operations, machine removal and installation verification allow up to 60 seconds of polling for registry/package state to settle. The user's Teams add-in removal has the same allowance. Reads that fail still raise an error; inaccessible state is not treated as proof that an app is gone.
|
||||
- After successful operations, machine removal and installation verification allow up to 60 seconds of polling for registry/package state to settle. The user's Teams add-in removal has the same allowance. Get Help's explicitly asynchronous removal uses the longer background wait described above. Reads that fail still raise an error; inaccessible state is not treated as proof that an app is gone.
|
||||
- Appx removal checks whether the exact package disappeared even when the removal command reports an error. If it remains, removal retries up to three times, each followed by the verification wait. Installed and provisioned packages must both be absent before continuing.
|
||||
- A process that exits just before forced shutdown is tolerated. Failure to unregister an already-completed cleanup task is logged and does not stop installation; its completion marker makes subsequent task runs a no-op.
|
||||
|
||||
@@ -127,7 +129,7 @@ The installer verifies the selected Office product, bitness, and downloaded vers
|
||||
|
||||
## Verification
|
||||
|
||||
Run `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\Install-MicrosoftOffice365.Tests.ps1` for offline checks. They require Windows PowerShell 5.1 and exercise the default validation gate (including `Force`), explicit deployment opt-out, log/console routing with the real Tools helpers, XML, removal-result handling, bounded cache deletion, companion installer failures/verification, deferred cleanup protection, and the unchanged `Run-Script` receiving injected strings through the shim with a mocked workload. Recovery checks simulate busy MSI, delayed registration, transient downloads, Appx removal races, persistent failures, and completed-task housekeeping errors. An inert executable checks actual native argument passing; a 32-bit Windows PowerShell child checks relaunch into 64-bit Windows PowerShell 5.1 and exit-code propagation. They do not run Microsoft installers or clear actual credentials.
|
||||
Run `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\Install-MicrosoftOffice365.Tests.ps1` for offline checks. They require Windows PowerShell 5.1 and exercise the default validation gate (including `Force`), explicit deployment opt-out, log/console routing with the real Tools helpers, XML, removal-result handling, bounded cache deletion, companion installer failures/verification, deferred cleanup protection, and the unchanged `Run-Script` receiving injected strings through the shim with a mocked workload. Recovery checks simulate busy MSI, delayed registration, transient downloads, Appx removal races, persistent failures, and completed-task housekeeping errors. Get Help regression cases use captured usage text, both result formats, zero-exit argument errors, and background workers/registration delays/timeouts. An inert executable checks actual native argument passing; a 32-bit Windows PowerShell child checks relaunch into 64-bit Windows PowerShell 5.1 and exit-code propagation. They do not run Microsoft installers or clear actual credentials.
|
||||
|
||||
`Run-Script` is unchanged. Its existing local execution can read the Syncro variables from the enclosing caller scope. The Office workload validates those values and reports its own result and exit code. The shim only sets TLS, dot-sources `Tools.ps1`, and invokes the workload. Existing `Run-Script` bootstrap failure behavior also remains unchanged.
|
||||
|
||||
|
||||
@@ -37,6 +37,32 @@ try {
|
||||
# Exercise the real bounded retry loops without delaying offline tests.
|
||||
function Start-Sleep { param([int]$Seconds) $script:testSleeps += $Seconds }
|
||||
$script:testSleeps = @()
|
||||
# Captured from signed GetHelpCmd 1.0.0+d28f675 on 2026-10-14 using only -?.
|
||||
$currentGetHelpUsage = @'
|
||||
Starting Microsoft GetHelp Command Line Tool
|
||||
Usage: GetHelpCmd.exe [options]
|
||||
Options:
|
||||
-S <scenario> Run the specified scenario.
|
||||
-RemoveSCA Remove Shared Computer Activation.
|
||||
-IsOrgId Is OrgId account.
|
||||
-P <profile> Specify Outlook profile name.
|
||||
-LogFolder <folder> Specify log folder.
|
||||
-AcceptEula Accept the End-User License Agreement.
|
||||
-DisplayEULA Display the EULA URL.
|
||||
-Help Display online help.
|
||||
-? Display this help message.
|
||||
|
||||
Examples:
|
||||
GetHelpCmd.exe -S OfficeSharedComputerScenario -AcceptEula
|
||||
GetHelpCmd.exe -S OfficeActivationScenario -AcceptEula
|
||||
GetHelpCmd.exe -S OfficeScrubScenario -AcceptEula
|
||||
GetHelpCmd.exe -S ExpertExperienceAdminTask -AcceptEula
|
||||
GetHelpCmd.exe -S OutlookCalendarCheckTask -AcceptEula
|
||||
GetHelpCmd.exe -S OutlookEmailSetupScenario -AcceptEula
|
||||
GetHelpCmd.exe -S ResetOfficeActivation -AcceptEula
|
||||
GetHelpCmd.exe -S TeamsAddinScenario -AcceptEula
|
||||
'@
|
||||
$currentGetHelpSuccess = "Scenario completed successfully.`r`nExecutionResultDetails: Uninstall office is running in the background."
|
||||
& {
|
||||
$script:probeCalls=0; $script:testSleeps=@()
|
||||
$result = Wait-OfficeResult { $script:probeCalls++; if ($script:probeCalls -eq 3) { [pscustomobject]@{Version='ready'} } } 'delayed fixture registration'
|
||||
@@ -237,6 +263,9 @@ try {
|
||||
$script:mediaProcesses += [IO.Path]::GetFileName($FilePath)
|
||||
if ([IO.Path]::GetFileName($FilePath) -eq 'odt.exe' -and $Arguments -like '/quiet /extract:*') {
|
||||
[IO.File]::WriteAllText((Join-Path $mediaWorkspace 'ODT\setup.exe'), 'Inert ODT fixture; never executed.')
|
||||
} elseif ([IO.Path]::GetFileName($FilePath) -eq 'GetHelpCmd.exe' -and $Arguments -eq '-?') {
|
||||
[IO.File]::WriteAllText("$LogPrefix.stdout.log", $currentGetHelpUsage)
|
||||
[IO.File]::WriteAllText("$LogPrefix.stderr.log", '')
|
||||
} elseif ([IO.Path]::GetFileName($FilePath) -eq 'setup.exe' -and $Arguments -like '/download *') {
|
||||
$script:mediaDownloadCalls++
|
||||
if ($script:mediaDownloadCalls -eq 1) { return 12029 }
|
||||
@@ -252,7 +281,8 @@ try {
|
||||
Assert-OfficeTest ($media.Scrubber -in $script:mediaSignatures -and $media.Setup -in $script:mediaSignatures) 'Extracted Get Help and ODT must still pass signature checks.'
|
||||
Assert-OfficeTest ($media.Version -eq '16.0.12345.67890' -and $media.Companions.Count -eq 3 -and !$media.Companions.ContainsKey('Teams')) 'Media staging lost its build or no-Teams selection.'
|
||||
Assert-OfficeTest (([xml](Get-Content -LiteralPath $media.Config -Raw)).Configuration.Add.Version -eq $media.Version) 'Staged configuration must pin the downloaded build.'
|
||||
Assert-OfficeTest (($script:mediaProcesses -join ',') -eq 'odt.exe,setup.exe,setup.exe') 'Staging must retry the failed download without launching a scrubber or companion installer.'
|
||||
Assert-OfficeTest (($script:mediaProcesses -join ',') -eq 'odt.exe,GetHelpCmd.exe,setup.exe,setup.exe') 'Staging must probe Get Help usage and retry the failed download without starting a scrub scenario or companion installation.'
|
||||
Assert-OfficeTest ($media.ScrubArguments -eq '-S OfficeScrubScenario -AcceptEula') 'Staging must select the syntax supported by the downloaded scrubber.'
|
||||
}
|
||||
& {
|
||||
$script:staged = @(); $script:verified = @()
|
||||
@@ -369,6 +399,92 @@ try {
|
||||
Assert-OfficeThrows { Assert-OfficeScrubResult 0 'Starting scenario...' @() } 'no recognizable'
|
||||
Assert-OfficeThrows { Assert-OfficeScrubResult 1 '00: Success.' @() } 'removal failed'
|
||||
Assert-OfficeThrows { Assert-OfficeScrubResult 0 '68: No product.' @([pscustomobject]@{DisplayName='Office 2016'}) } 'Office remains'
|
||||
Assert-OfficeTest ((Get-OfficeScrubArguments 0 $currentGetHelpUsage) -eq '-S OfficeScrubScenario -AcceptEula') 'Current Get Help must not receive the rejected OfficeVersion switch.'
|
||||
Assert-OfficeTest ((Get-OfficeScrubArguments 0 ($currentGetHelpUsage + "`n -OfficeVersion <version> Specify version to remove.")) -eq '-S OfficeScrubScenario -AcceptEula -OfficeVersion All') 'Get Help builds advertising OfficeVersion must explicitly select All.'
|
||||
Assert-OfficeTest ((Get-OfficeScrubArguments 0 " -OfficeVersion <version>`nGetHelpCmd.exe -S OfficeScrubScenario -AcceptEula -OfficeVersion All") -eq '-S OfficeScrubScenario -AcceptEula -OfficeVersion All') 'A usage example with an optional version argument must also validate.'
|
||||
Assert-OfficeThrows { Get-OfficeScrubArguments 1 $currentGetHelpUsage } 'command syntax'
|
||||
Assert-OfficeThrows { Get-OfficeScrubArguments 0 'Usage: unrecognized executable' } 'command syntax'
|
||||
Assert-OfficeThrows { Get-OfficeScrubArguments 0 ("Error: Invalid command line arguments`n" + $currentGetHelpUsage) } 'command syntax'
|
||||
Assert-OfficeScrubResult 0 $currentGetHelpSuccess @()
|
||||
Assert-OfficeScrubResult 0 'Scenario completed successfully.' @()
|
||||
Assert-OfficeThrows { Assert-OfficeScrubResult 0 ("Error: Invalid command line arguments`n" + $currentGetHelpUsage) @() } 'removal failed.*Invalid command line arguments'
|
||||
Assert-OfficeThrows { Assert-OfficeScrubResult 0 " - Uninstall Office Scenario failed.`nAccess denied." @() } 'removal failed.*Access denied'
|
||||
Assert-OfficeThrows { Assert-OfficeScrubResult 0 ($currentGetHelpSuccess + "`nError: failed after launch") @() } 'removal failed'
|
||||
Assert-OfficeThrows { Assert-OfficeScrubResult 0 ($currentGetHelpSuccess + "`n09: Failure to remove Office.") @() } 'removal failed'
|
||||
Assert-OfficeThrows { Assert-OfficeScrubResult 0 "09: Failed`n00: Completed" @() } 'removal failed'
|
||||
Assert-OfficeThrows { Assert-OfficeScrubResult 1 $currentGetHelpSuccess @() } 'no recognizable successful'
|
||||
Assert-OfficeThrows { Assert-OfficeScrubResult 0 'Diagnostic action completed.' @() } 'no recognizable successful'
|
||||
Assert-OfficeThrows { Assert-OfficeScrubResult 0 $currentGetHelpSuccess @([pscustomobject]@{DisplayName='Office 2021'}) } 'Office remains'
|
||||
& {
|
||||
function Get-CimInstance {
|
||||
param($ClassName,$Filter)
|
||||
Assert-OfficeTest ($ClassName -eq 'Win32_Process' -and $Filter -match 'powershell.exe') 'Background scrub checks must query process state, not MSI product repair inventory.'
|
||||
[pscustomobject]@{ProcessId=$PID; Name='powershell.exe'; CommandLine='deployment host'}
|
||||
[pscustomobject]@{ProcessId=101; Name='msiexec.exe'; CommandLine='C:\Windows\System32\msiexec.exe /V'}
|
||||
[pscustomobject]@{ProcessId=102; Name='msiexec.exe'; CommandLine='msiexec.exe /Embedding guid'}
|
||||
[pscustomobject]@{ProcessId=103; Name='OfficeClickToRun.exe'; CommandLine='OfficeClickToRun.exe /service'}
|
||||
[pscustomobject]@{ProcessId=104; Name='msiexec.exe'; CommandLine='msiexec.exe /x fixture /qn'}
|
||||
[pscustomobject]@{ProcessId=105; Name='powershell.exe'; CommandLine='powershell.exe -File OfficeUninstall.ps1'}
|
||||
}
|
||||
$workers = @(Get-OfficeScrubWorkers)
|
||||
Assert-OfficeTest (($workers.ProcessId -join ',') -eq '104,105') 'Only client/script workers should block background completion; exclude this host and idle service hosts.'
|
||||
}
|
||||
$realOfficeDefinitions = ${function:Get-OfficeDeploymentDefinitions}
|
||||
& {
|
||||
function Get-OfficeDeploymentDefinitions {
|
||||
$values = & $realOfficeDefinitions
|
||||
$values.ScrubBackgroundCheckAttempts=10; $values.ScrubBackgroundQuietChecks=3
|
||||
$values
|
||||
}
|
||||
function Get-OfficeSuiteInventory {
|
||||
$script:scrubChecks++
|
||||
if ($script:scrubMode -eq 'read-error') { throw 'Office inventory is unreadable' }
|
||||
if ($script:scrubMode -eq 'remaining' -or ($script:scrubMode -eq 'delayed' -and $script:scrubChecks -le 2) -or ($script:scrubMode -eq 'reappears' -and $script:scrubChecks -eq 3)) { [pscustomobject]@{DisplayName='Fixture Office 2021'} }
|
||||
}
|
||||
function Get-OfficeScrubWorkers {
|
||||
[pscustomobject]@{ProcessId=200; CreationDate='old'; Name='powershell.exe'; CommandLine='existing console'}
|
||||
if ($script:scrubMode -eq 'worker' -or ($script:scrubMode -eq 'delayed' -and $script:scrubChecks -le 4)) {
|
||||
# Reused PID with a new creation time must not be mistaken for a baseline process.
|
||||
[pscustomobject]@{ProcessId=201; CreationDate='new'; Name='powershell.exe'; CommandLine='detached cleanup'}
|
||||
}
|
||||
}
|
||||
$baseline = @([pscustomobject]@{ProcessId=200; CreationDate='old'},[pscustomobject]@{ProcessId=201; CreationDate='old'})
|
||||
foreach ($script:scrubMode in @('empty','delayed','reappears','remaining','worker','read-error')) {
|
||||
$script:scrubChecks=0
|
||||
if ($script:scrubMode -in @('remaining','worker')) {
|
||||
Assert-OfficeThrows { Wait-OfficeScrubRemoval $baseline } 'background removal did not finish'
|
||||
Assert-OfficeTest ($script:scrubChecks -eq 10) 'Background removal must stop at its configured bound.'
|
||||
} elseif ($script:scrubMode -eq 'read-error') {
|
||||
Assert-OfficeThrows { Wait-OfficeScrubRemoval $baseline } 'Office inventory is unreadable'
|
||||
} else {
|
||||
$output = @(Wait-OfficeScrubRemoval $baseline)
|
||||
$expectedChecks = switch ($script:scrubMode) { 'empty' {3}; 'delayed' {7}; 'reappears' {6} }
|
||||
Assert-OfficeTest ($output.Count -eq 0 -and $script:scrubChecks -eq $expectedChecks) "Background removal skipped worker completion or its quiet interval: $script:scrubMode."
|
||||
}
|
||||
}
|
||||
}
|
||||
& {
|
||||
function Get-OfficeScrubWorkers { }
|
||||
function Get-OfficeSuiteInventory { }
|
||||
function Wait-OfficeScrubRemoval { $script:backgroundWaits++ }
|
||||
function Invoke-OfficeProcess {
|
||||
param($FilePath,$Arguments,$LogPrefix)
|
||||
Assert-OfficeTest ($Arguments -eq '-S OfficeScrubScenario -AcceptEula') 'Removal must use the command validated during staging.'
|
||||
[IO.File]::WriteAllText("$LogPrefix.stdout.log", $script:scrubOutput)
|
||||
[IO.File]::WriteAllText("$LogPrefix.stderr.log", '')
|
||||
0
|
||||
}
|
||||
$media = [pscustomobject]@{Scrubber='inert.exe'; ScrubArguments='-S OfficeScrubScenario -AcceptEula'}
|
||||
$script:backgroundWaits=0; $script:scrubOutput=$currentGetHelpSuccess
|
||||
Remove-OfficeSuite $media $testRoot
|
||||
Assert-OfficeTest ($script:backgroundWaits -eq 1) 'Background acknowledgement must trigger the extended completion check.'
|
||||
$script:scrubOutput='00: Successfully completed this scenario.'
|
||||
Remove-OfficeSuite $media $testRoot
|
||||
Assert-OfficeTest ($script:backgroundWaits -eq 1) 'A synchronous result should use ordinary removal verification.'
|
||||
$script:scrubOutput="Error: Invalid command line arguments`n$currentGetHelpUsage"
|
||||
Assert-OfficeThrows { Remove-OfficeSuite $media $testRoot } 'Invalid command line arguments'
|
||||
Assert-OfficeTest ($script:backgroundWaits -eq 1) 'A failed launch must fail before background waiting or installation.'
|
||||
}
|
||||
Assert-OfficeTest (Test-OfficeCredentialTarget 'MicrosoftOffice16_Data:ADAL:example') 'Office ADAL credential should be cleared.'
|
||||
foreach ($target in @('WindowsLive:target', 'MicrosoftAccount:user', 'OneDrive:user', 'AzureAD:user', 'TERMSRV/server', 'MicrosoftOffice16_DataEvil')) { Assert-OfficeTest (!(Test-OfficeCredentialTarget $target)) "Unrelated credential matched: $target" }
|
||||
Assert-OfficeTest ('Microsoft.AAD.BrokerPlugin' -notin (Get-OfficeAppxNames)) 'Must preserve Windows work-account broker.'
|
||||
|
||||
Reference in New Issue
Block a user