add scrubber back into deployment script

This commit is contained in:
2026-10-29 15:05:37 -04:00
parent 3e24920646
commit 52aa59a70c
5 changed files with 283 additions and 38 deletions
+115 -17
View File
@@ -32,6 +32,10 @@ function Get-OfficeDeploymentDefinitions {
OdtPage = 'https://www.microsoft.com/en-us/download/details.aspx?id=49117'
OdtDownloadPattern = 'https://download\.microsoft\.com/[^"\s<>]+/officedeploymenttool_[a-zA-Z0-9_-]+\.exe'
ManualScrubUrl = 'https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall'
GetHelpUrl = 'https://aka.ms/SaRA_EnterpriseVersionFiles'
GetHelpExecutable = 'GetHelpCmd.exe'
ScrubArguments = '-S OfficeScrubScenario -AcceptEula -OfficeVersion All'
ScrubRecoveryExitCodes = @(17002, 17004)
HelperVersion = 'EmberkomOfficeUserCleanup-v5'
Language = 'en-us'
OfficeBuildPattern = '^16\.0\.\d+\.\d+$'
@@ -250,7 +254,7 @@ function Test-OfficeDownloadLinks {
param($Options)
$definitions = Get-OfficeDeploymentDefinitions
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$links = @($definitions.OdtPage, "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1")
$links = @($definitions.OdtPage, "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1", $definitions.GetHelpUrl)
if ($Options.OfficeFeatureRelease) { $links += $definitions.OfficeReleaseHistory }
$channel = $definitions.OfficeCdnChannels[$Options.UpdateChannel]
$links += "https://officecdn.microsoft.com/pr/$channel/Office/Data/v$($Options.OfficeArchitecture).cab"
@@ -406,8 +410,9 @@ function Test-OfficeStagingInUse {
param([string]$Workspace, [object[]]$Processes)
# Be conservative even when a child installer no longer names its source folder.
foreach ($process in $Processes) {
if ($process.Name -in @('setup.exe', 'odt.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe')) { return $true }
if ($process.Name -in @('setup.exe', 'odt.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'GetHelpCmd.exe', 'SaRAcmd.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe')) { return $true }
if ($process.Name -eq 'OfficeClickToRun.exe' -and $process.CommandLine -notmatch '(?i)\s/(service|user)\s*$') { return $true }
if ($process.CommandLine -match '(?i)\b(OffScrub[^\s"\\/]*\.(vbs|ps1)|OfficeScrubScenario)\b') { return $true }
foreach ($value in @($process.CommandLine, $process.ExecutablePath)) {
if ($value -and $value.IndexOf($Workspace, [StringComparison]::OrdinalIgnoreCase) -ge 0) { return $true }
}
@@ -525,7 +530,7 @@ function Invoke-OfficeProcess {
}
}
function Write-OfficeSetupDiagnostics {
function Get-OfficeSetupLogFiles {
param(
[DateTime]$SinceUtc,
[string[]]$SearchRoots = @([IO.Path]::GetTempPath(), "$env:WINDIR\Temp", "$env:WINDIR\SystemTemp")
@@ -542,7 +547,16 @@ function Write-OfficeSetupDiagnostics {
}
} catch { $null = Write-Output "Could not search native Office logs in ${root}: $($_.Exception.Message)" }
})
$files = @($files | Sort-Object FullName -Unique | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First $definitions.SetupDiagnosticFileLimit)
$files | Sort-Object FullName -Unique | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First $definitions.SetupDiagnosticFileLimit
}
function Write-OfficeSetupDiagnostics {
param(
[DateTime]$SinceUtc,
[string[]]$SearchRoots = @([IO.Path]::GetTempPath(), "$env:WINDIR\Temp", "$env:WINDIR\SystemTemp")
)
$definitions = Get-OfficeDeploymentDefinitions
$files = @(Get-OfficeSetupLogFiles -SinceUtc $SinceUtc -SearchRoots $SearchRoots)
if (!$files.Count) {
$null = Write-Output "No recent nonempty native Office logs found in: $($SearchRoots -join '; '). Empty ODT stdout/stderr files do not contain the underlying setup error."
return
@@ -832,21 +846,94 @@ function Get-OfficeClickToRunState {
[pscustomobject]@{ Present=($present -or $null -ne $service); SourceReferences=$sources; WorkingConfiguration=$working }
}
function Assert-OfficeFreshInstallState {
$cleared = Wait-OfficeResult {
function Test-OfficeFreshInstallState {
[bool](Wait-OfficeResult {
$state = Get-OfficeClickToRunState
!$state.SourceReferences.Count -and !$state.WorkingConfiguration.Count
} 'removal of previous Click-to-Run working configuration and deployment source references'
if (!$cleared) {
} 'removal of previous Click-to-Run working configuration and deployment source references')
}
function Assert-OfficeFreshInstallState {
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 {
param([DateTime]$SinceUtc)
$finishedUtc = [DateTime]::UtcNow
foreach ($file in @(Get-OfficeSetupLogFiles -SinceUtc $SinceUtc)) {
try {
foreach ($line in @(Get-Content -LiteralPath $file.FullName -Tail (Get-OfficeDeploymentDefinitions).SetupDiagnosticTailLines -ErrorAction Stop)) {
# An exit code alone cannot distinguish corrupt state from network,
# source or policy problems. Require a removal-specific native error
# timestamped during THIS attempt, not an old error in a live log.
if ($line -notmatch '(?i)InvalidDirectory' -or $line -notmatch '(?i)REMOVEINSTALLATION') { continue }
if ($line -notmatch '^\s*(\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2}:\d{2}\.\d{3})\s') { continue }
$stamp = [DateTime]::MinValue
if (![DateTime]::TryParseExact($Matches[1], 'M/d/yyyy H:mm:ss.fff', [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::AssumeLocal, [ref]$stamp)) { continue }
if ($stamp.ToUniversalTime() -lt $SinceUtc.AddSeconds(-1) -or $stamp.ToUniversalTime() -gt $finishedUtc) { continue }
return [pscustomobject]@{ Path=$file.FullName; Detail=$line }
}
} catch { $null = Write-Output "Could not classify Office removal failure from $($file.FullName): $($_.Exception.Message)" }
}
}
function Initialize-OfficeScrubMedia {
param([string]$Workspace)
$definitions = Get-OfficeDeploymentDefinitions
$archivePath = Join-Path $Workspace 'GetHelp.zip'
$folder = Join-Path $Workspace 'GetHelp'
if ((Test-Path -LiteralPath $archivePath) -or (Test-Path -LiteralPath $folder)) { throw 'Scrub media already exists in this run; refusing to reuse it or repeat recovery.' }
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Save-OfficeDownload $definitions.GetHelpUrl $archivePath
# Validate every entry before extraction, including on older PS 5.1 archive modules.
Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem
$archive = [IO.Compression.ZipFile]::OpenRead($archivePath)
try {
foreach ($entry in $archive.Entries) {
if (!$entry.FullName -or $entry.FullName.Contains(':')) { throw 'Unexpected path in Get Help archive.' }
Assert-OfficeManagedPath $folder ([IO.Path]::Combine($folder, $entry.FullName))
}
} finally { $archive.Dispose() }
# Tools.ps1 overrides Expand-Archive with a Path-only wrapper.
Microsoft.PowerShell.Archive\Expand-Archive -LiteralPath $archivePath -DestinationPath $folder -ErrorAction Stop
$files = @(Get-OfficeManagedFiles $Workspace $folder)
$executables = @($files | Where-Object { $_.Name -eq $definitions.GetHelpExecutable })
if ($executables.Count -ne 1) { throw "Microsoft download did not contain exactly one $($definitions.GetHelpExecutable)." }
Assert-OfficeMicrosoftSignature $executables[0].FullName
$executables[0].FullName
}
function Invoke-OfficeScrubRecovery {
param($Media, [string]$Workspace, [string]$Reason)
if ($Media.ScrubAttempted) { throw 'Office scrub recovery was already attempted. Installation stopped; no repeated scrub or install loop will run.' }
$Media | Add-Member -NotePropertyName ScrubAttempted -NotePropertyValue $true -Force
$Media | Add-Member -NotePropertyName ScrubReason -NotePropertyValue $Reason -Force
$null = Write-Output "Office scrub recovery selected: $Reason"
$null = Write-Output 'Running one Microsoft Get Help OfficeScrubScenario attempt. It removes all Office versions, including Visio/Project. Get Help may display a child window despite the hidden launch.'
$scrubber = Initialize-OfficeScrubMedia $Workspace
$prefix = Join-Path $Workspace 'office-scrub'
$code = Invoke-OfficeProcess $scrubber (Get-OfficeDeploymentDefinitions).ScrubArguments $prefix
$output = (Get-Content -LiteralPath "$prefix.stdout.log" -Raw -ErrorAction Stop) + "`n" + (Get-Content -LiteralPath "$prefix.stderr.log" -Raw -ErrorAction Stop)
$results = @([regex]::Matches($output, '(?m)^\s*(\d{2}):') | ForEach-Object { $_.Groups[1].Value })
$null = Write-Output "Get Help scrub result: process $code; scenario results $($results -join ', '). Logs: $prefix"
# 66/68 mean Office was not found, not a verified repair of damaged state.
if ($code -notin @(0, 3010) -or !$results.Count -or @($results | Where-Object { $_ -ne '00' }).Count) { throw "Get Help scrub failed or returned an unverified result (process $code; scenarios $($results -join ', ')). Installation stopped. See $prefix.stdout.log and $prefix.stderr.log." }
$idle = Wait-OfficeResult { !(Test-OfficeStagingInUse $Workspace @(Get-CimInstance Win32_Process -ErrorAction Stop)) } 'Office scrub child processes to finish'
if (!$idle) { throw 'Office scrub processes are still running. Installation stopped to avoid concurrent removal and installation.' }
$removed = Wait-OfficeResult { @(Get-OfficeSuiteInventory).Count -eq 0 } 'all Office registrations to disappear after Get Help scrub'
if (!$removed) { throw "Office remains after Get Help scrub: $((Get-OfficeSuiteInventory).DisplayName -join '; '). Installation stopped." }
Assert-OfficeFreshInstallState
$null = Write-Output 'Office scrub recovery verified. Reporting restart required; DeferReboot controls whether installation can finish before that restart.'
return 3010
}
function Remove-OfficeSuite {
param($Media, [string]$Workspace)
# Get Help can create an interactive elevated child despite a hidden SYSTEM parent.
# Never fall back to it automatically. ODT owns the supported silent removal path.
# ODT is the normal path. A single Get Help scrub is reserved for evidence of
# broken removal or residual state, before replacement installation begins.
$existing = @(Get-OfficeSuiteInventory)
$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 '; ')." }
@@ -857,15 +944,25 @@ function Remove-OfficeSuite {
}
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.'
$startedUtc = [DateTime]::UtcNow
$code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.RemovalConfig)`"" (Join-Path $Workspace 'office-remove')
$manual = "No interactive scrubber was launched. Arrange an attended manual scrub if needed: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)"
if ($code -notin @(0, 3010)) { throw "Silent ODT Office removal failed (exit $code). See logs in $Workspace. $manual" }
if ($code -notin @(0, 3010)) {
if ($code -in (Get-OfficeDeploymentDefinitions).ScrubRecoveryExitCodes) {
$evidence = Get-OfficeRemovalCorruptionEvidence -SinceUtc $startedUtc
if ($evidence) {
$null = Write-Output "Office scrub trigger evidence: $($evidence.Path) : $($evidence.Detail)"
return Invoke-OfficeScrubRecovery $Media $Workspace "ODT removal exit $code with a current REMOVEINSTALLATION InvalidDirectory error."
}
}
throw "Silent ODT Office removal failed (exit $code). No confirmed removal-corruption evidence was found; automatic scrub was not selected. See logs in $Workspace. Manual troubleshooting: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)"
}
if ($code -eq 3010) { return 3010 }
$removed = Wait-OfficeResult { @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 }).Count -eq 0 } 'Click-to-Run Office removal registration'
if (!$removed) {
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 })
throw "Office remains after silent ODT removal: $($remaining.DisplayName -join '; '). Installation stopped. $manual"
return Invoke-OfficeScrubRecovery $Media $Workspace "Office remains after successful ODT removal: $($remaining.DisplayName -join '; ')."
}
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
}
@@ -1129,11 +1226,11 @@ function Install-OfficeMedia {
param($Options, $Media, [string]$Workspace)
$msi = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 })
$code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.Config)`"" (Join-Path $Workspace 'office-install')
if ($code -notin @(0, 3010)) { throw "Office installation failed (exit $code). Diagnostic logs remain in $Workspace; disposable media is cleaned up after installer processes finish. Review the Native Office log/detail entries in the diagnostic log; Click-to-Run writes its underlying errors to the execution account's temp folder or Windows\Temp. The exit code alone does not identify the cause. No interactive scrubber was launched." }
if ($code -notin @(0, 3010)) { throw "Office installation failed (exit $code). Diagnostic logs remain in $Workspace; disposable media is cleaned up after installer processes finish. Review the Native Office log/detail entries in the diagnostic log; Click-to-Run writes its underlying errors to the execution account's temp folder or Windows\Temp. The exit code alone does not identify the cause. No automatic scrub is attempted after replacement installation begins." }
$msiRemoved = Wait-OfficeResult { @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 }).Count -eq 0 } 'legacy MSI Office removal by ODT'
if (!$msiRemoved) {
$remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 })
throw "MSI Office remains after ODT RemoveMSI: $($remaining.DisplayName -join '; '). Deployment is incomplete; the new suite may already be installed. No interactive scrubber was launched. Arrange an attended manual scrub if needed: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)"
throw "MSI Office remains after ODT RemoveMSI: $($remaining.DisplayName -join '; '). Deployment is incomplete; the new suite may already be installed. No automatic scrub is attempted after replacement installation begins. Arrange an attended manual scrub if needed: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)"
}
$platform = if ($Options.OfficeArchitecture -eq '64') { 'x64' } else { 'x86' }
$verified = Wait-OfficeResult {
@@ -1193,6 +1290,7 @@ function Invoke-OfficeDeployment {
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
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.'
NextStep='Set ValidateBeforeChanges=false to download, verify, deploy, and clean up installation media. Prerequisites are checked again.'
}
}
@@ -1215,7 +1313,7 @@ function Invoke-OfficeDeployment {
$removalCode = Remove-OfficeSuite $media $workspace
if ($removalCode -eq 3010 -and !(Test-OfficeCanDeferRestart $Options 'Office')) {
$null = Write-Output 'Office removal requires a restart. Restart and rerun; replacement installation has not started.'
$receipt = [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @(); ArtifactCleanupPending=$false }
$receipt = [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @(); ArtifactCleanupPending=$false; ScrubRecoveryAttempted=[bool]$media.ScrubAttempted; ScrubRecoveryReason=$media.ScrubReason }
return $receipt
}
Assert-OfficeFreshInstallState
@@ -1235,7 +1333,7 @@ function Invoke-OfficeDeployment {
$null = Write-Output "$provisionedApps provisioned for all users; OneDrive is installed per-machine. Users may need to sign out and back in to register the apps."
$null = Write-Output 'Windows work-account/WAM sign-in is preserved; Windows SSO can sign Office in again. App installation does not grant Teams or mailbox entitlements.'
$completed = $true
$receipt = [pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if (($pending.Count -or $registrationFailures.Count) -and $code -eq 0) { 2 } else { $code }); RestartRequired=($code -eq 3010); DeferReboot=$Options.DeferReboot; ValidateBeforeChanges=$false; Workspace = $workspace; UserCleanupWorkspace=$(if ($profiles.Count) { $userWorkspace } else { $null }); PendingUserSids = $pending; UserCleanupRegistrationFailures = $registrationFailures; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version; MediaDownloaded=$true; ArtifactCleanupPending=$false }
$receipt = [pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if (($pending.Count -or $registrationFailures.Count) -and $code -eq 0) { 2 } else { $code }); RestartRequired=($code -eq 3010); DeferReboot=$Options.DeferReboot; ValidateBeforeChanges=$false; Workspace = $workspace; UserCleanupWorkspace=$(if ($profiles.Count) { $userWorkspace } else { $null }); PendingUserSids = $pending; UserCleanupRegistrationFailures = $registrationFailures; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version; MediaDownloaded=$true; ArtifactCleanupPending=$false; ScrubRecoveryAttempted=[bool]$media.ScrubAttempted; ScrubRecoveryReason=$media.ScrubReason }
return $receipt
} finally {
if ($workspace) {