drop the scrubber from the script

add a variable to defer reboot after uninstall
This commit is contained in:
2026-10-14 23:09:54 -04:00
parent e3fe378b41
commit a61b3bb6a3
4 changed files with 291 additions and 274 deletions
+100 -126
View File
@@ -31,23 +31,7 @@ function Get-OfficeDeploymentDefinitions {
RepositoryRoot = 'https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master'
OdtPage = 'https://www.microsoft.com/en-us/download/details.aspx?id=49117'
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'
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')
ManualScrubUrl = 'https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall'
HelperVersion = 'EmberkomOfficeUserCleanup-v4'
Language = 'en-us'
OfficeBuildPattern = '^16\.0\.\d+\.\d+$'
@@ -81,11 +65,13 @@ function Get-OfficeDeploymentDefinitions {
OdtPageTimeoutSeconds = 120
MsiBusyAttempts = 5
MsiBusyRetrySeconds = 15
RegistrationCheckAttempts = 13
# Installer processes have no separate elapsed-time cutoff; Syncro owns the
# overall run limit (configure 120 minutes). These are post-process checks.
RegistrationCheckAttempts = 61
RegistrationCheckSeconds = 5
AppxRemovalAttempts = 3
UserCleanupWaitMinutes = 5
UserCleanupTaskMinutes = 15
UserCleanupWaitMinutes = 20
UserCleanupTaskMinutes = 30
}
}
@@ -97,6 +83,9 @@ function Get-OfficeDeploymentOptions {
[string]$validate = $InputValues.ValidateBeforeChanges
if ([string]::IsNullOrWhiteSpace($validate)) { $validate = 'true' }
$validateOnly = ConvertTo-RmmBoolean -Value $validate -VariableName 'ValidateBeforeChanges'
[string]$defer = $InputValues.DeferReboot
if ([string]::IsNullOrWhiteSpace($defer)) { $defer = 'true' }
$deferReboot = ConvertTo-RmmBoolean -Value $defer -VariableName 'DeferReboot'
[string]$subscription = $InputValues.OfficeSubscription
$subscription = $subscription.Trim()
# Accept previously documented individual names for existing saved RMM selections.
@@ -110,7 +99,7 @@ function Get-OfficeDeploymentOptions {
[string]$company = $InputValues.COMPANY
$company = $company.Trim()
if ($company -eq 'None') { $company = '' }
$options = @{ OfficeSubscription = $subscription; ProductId = $plans[$subscription]; Company = $company; ValidateBeforeChanges = $validateOnly }
$options = @{ OfficeSubscription = $subscription; ProductId = $plans[$subscription]; Company = $company; ValidateBeforeChanges = $validateOnly; DeferReboot = $deferReboot }
# Derive this from the validated product mapping, including standalone Apps plans and legacy aliases.
$options.InstallTeams = $options.ProductId -in $definitions.TeamsProducts
foreach ($name in $choices.Keys) {
@@ -270,6 +259,19 @@ function New-OfficeConfiguration {
return ,$xml
}
function New-OfficeRemovalConfiguration {
param($Options)
$xml = New-Object Xml.XmlDocument
$configuration = $xml.CreateElement('Configuration'); $null = $xml.AppendChild($configuration)
$remove = $xml.CreateElement('Remove'); $remove.SetAttribute('All', 'TRUE'); $null = $configuration.AppendChild($remove)
$display = $xml.CreateElement('Display'); $display.SetAttribute('Level', 'None'); $display.SetAttribute('AcceptEULA', 'TRUE'); $null = $configuration.AppendChild($display)
$property = $xml.CreateElement('Property'); $property.SetAttribute('Name', 'FORCEAPPSHUTDOWN')
$property.SetAttribute('Value', $(if ($Options.OfficeAppShutdown -eq 'Force') { 'TRUE' } else { 'FALSE' })); $null = $configuration.AppendChild($property)
# Remove applies to Click-to-Run. RemoveMSI belongs to the installation configuration:
# ODT removes MSI Office before installing the replacement product in that operation.
return ,$xml
}
function Initialize-OfficeMedia {
param($Options, [string]$Workspace)
$definitions = Get-OfficeDeploymentDefinitions
@@ -285,24 +287,8 @@ function Initialize-OfficeMedia {
$code = Invoke-OfficeProcess $package "/quiet /extract:`"$odtFolder`"" (Join-Path $Workspace 'odt-extract')
if ($code -ne 0) { throw "ODT extraction failed ($code)." }
$setup = Join-Path $odtFolder 'setup.exe'; Assert-OfficeMicrosoftSignature $setup
# Microsoft's evergreen Get Help link retains its historical SaRA name.
$scrubZip = Join-Path $Workspace 'GetHelp.zip'
Save-OfficeDownload $definitions.GetHelpUrl $scrubZip
$scrubFolder = Join-Path $Workspace 'GetHelp'
$null = Write-Output "Extracting Get Help: $scrubZip -> $scrubFolder"
# Tools.ps1 overrides Expand-Archive with a Path-only wrapper. Use the PS 5.1
# module explicitly for literal paths, while keeping diagnostics in the Tools log.
Microsoft.PowerShell.Archive\Expand-Archive -LiteralPath $scrubZip -DestinationPath $scrubFolder -ErrorAction Stop
$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"
$removalPath = Join-Path $Workspace 'remove.xml'
$removal = New-OfficeRemovalConfiguration $Options; $removal.Save($removalPath)
# 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
@@ -328,7 +314,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; ScrubArguments = $scrubArguments; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions }
[pscustomobject]@{ Setup = $setup; RemovalConfig = $removalPath; Config = $configPath; Helper = $helper; Version = $versions[0].Name; Companions = $companions }
}
function Get-OfficeRunningApps {
@@ -460,84 +446,58 @@ function Get-OfficeSuiteInventory {
$_.DisplayName -match '(?i)^(Microsoft\s+)?(365|Office|Visio|Project|Access|Word|Excel|Outlook|PowerPoint|OneNote|Publisher|Skype for Business)(\s|$)' -and
$_.DisplayName -notmatch '(?i)(Add-in|Addin|Redistributable|Database Engine|Extensibility|Update|Hotfix|Click-to-Run)'
}
$c2r = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration' -ErrorAction SilentlyContinue
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."
$key = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration'
if (Test-Path -LiteralPath $key -ErrorAction Stop) {
$c2r = Get-ItemProperty -LiteralPath $key -ErrorAction Stop
if ($c2r.ProductReleaseIds) { [pscustomobject]@{ DisplayName = "Click-to-Run: $($c2r.ProductReleaseIds)" } }
}
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) {
$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'
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 @()
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)
# 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.
$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 '; ')." }
if (!@($existing | Where-Object { $_.WindowsInstaller -ne 1 }).Count) {
$null = Write-Output 'No non-MSI Office products detected; skipping the separate ODT removal pass.'
return 0
}
if (!$Media.RemovalConfig -or !(Test-Path -LiteralPath $Media.RemovalConfig -PathType Leaf)) { throw 'The staged silent Office removal configuration is missing.' }
$null = Write-Output 'Silently removing Click-to-Run Office, including Visio and Project, with ODT.'
$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 -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 0
}
function Test-OfficeCanDeferRestart {
param($Options, [ValidateSet('Office', 'Companions')][string]$Stage)
if ($Options.DeferReboot -isnot [bool]) { throw 'DeferReboot must be a validated Boolean before deciding whether to continue.' }
if (!$Options.DeferReboot) {
$null = Write-Output "$Stage removal requested a restart. DeferReboot=false; stopping before replacement installation."
return $false
}
# A 3010 result is success with a restart pending, not permission to ignore
# incomplete removal. Verify the old products are gone before deferring it.
$verified = Wait-OfficeResult {
if ($Stage -eq 'Office') { return @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 }).Count -eq 0 }
@(Get-OfficeMachineCompanionEntries).Count -eq 0
} "$Stage removal before deferring its restart"
if ($verified) {
$null = Write-Output "$Stage removal verified. Deferring the requested restart until after deployment; the final result will retain exit code 3010."
return $true
}
$remaining = @(if ($Stage -eq 'Office') { Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -ne 1 } } else { Get-OfficeMachineCompanionEntries })
$null = Write-Output "Cannot defer the $Stage removal restart: registrations remain for $($remaining.DisplayName -join '; '). Restart and rerun before replacement installation."
return $false
}
function Get-OfficeAppxNames {
@@ -660,7 +620,7 @@ function Remove-OfficeCompanionApps {
if ($remaining.Count) {
$details = ($remaining | ForEach-Object { "$($_.DisplayName) $($_.DisplayVersion) [$($_.PSPath)]" }) -join '; '
$null = Write-Output "Machine companion registrations remaining after removal: $details"
if (!$reboot) { throw "Machine companion registrations remain after removal: $details. Check uninstall logs in $Workspace. Office scrub/installation has not started." }
if (!$reboot) { throw "Machine companion registrations remain after removal: $details. Check uninstall logs in $Workspace. Office removal/installation has not started." }
}
$reboot
}
@@ -747,8 +707,14 @@ function Start-OfficeUserCleanup {
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). Media and logs remain in $Workspace." }
if ($code -notin @(0, 3010)) { throw "Office installation failed (exit $code). Media and logs remain in $Workspace. If old Office needs repair, arrange an attended manual scrub: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl). No interactive scrubber was launched." }
$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)"
}
$platform = if ($Options.OfficeArchitecture -eq '64') { 'x64' } else { 'x86' }
$verified = Wait-OfficeResult {
$key = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration'
@@ -757,6 +723,8 @@ function Install-OfficeMedia {
$Options.ProductId -in ($installed.ProductReleaseIds -split ',') -and $installed.Platform -eq $platform -and $installed.VersionToReport -eq $Media.Version
} 'the selected Office product, architecture, and version'
if (!$verified) { throw 'Setup exited successfully but the installed product, architecture, or version did not match.' }
# Microsoft requires a restart to finish MSI removal even when setup doesn't enforce it.
if ($msi.Count) { $null = Write-Output 'Legacy MSI Office removal was verified. A restart is required to finish removal; no automatic reboot was requested.'; return 3010 }
$code
}
@@ -766,6 +734,7 @@ function Invoke-OfficeDeployment {
# Internal action messages use Tools.ps1's logger. Suppress its echoed success output
# so it cannot become part of a function's return value. Entry prints the Syncro receipt.
if ($Options.ValidateBeforeChanges -isnot [bool]) { throw 'ValidateBeforeChanges must be a validated Boolean before running the workload.' }
if ($Options.DeferReboot -isnot [bool]) { throw 'DeferReboot must be a validated Boolean before running the workload.' }
Assert-OfficeDeploymentHost $Options
$mutex = New-Object Threading.Mutex($false, 'Global\EmberkomOfficeDeployment')
$locked = $false
@@ -775,7 +744,7 @@ function Invoke-OfficeDeployment {
$runningApps = @(Get-OfficeRunningApps | Select-Object -ExpandProperty ProcessName -Unique)
if ($runningApps.Count -and $Options.OfficeAppShutdown -eq 'Abort') { throw "Apps are running: $($runningApps -join ', '). Close them or select OfficeAppShutdown=Force for the maintenance window." }
$workspace = New-OfficeWorkspace
$null = Write-Output "Office request: $($Options.OfficeSubscription) / $($Options.ProductId), $($Options.OfficeArchitecture)-bit, $($Options.UpdateChannel), ValidateBeforeChanges=$($Options.ValidateBeforeChanges). Workspace: $workspace"
$null = Write-Output "Office request: $($Options.OfficeSubscription) / $($Options.ProductId), $($Options.OfficeArchitecture)-bit, $($Options.UpdateChannel), ValidateBeforeChanges=$($Options.ValidateBeforeChanges), DeferReboot=$($Options.DeferReboot). Workspace: $workspace"
$Options | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $workspace 'options.json') -Encoding UTF8
$profiles = @(Get-CimInstance Win32_UserProfile -ErrorAction Stop | Where-Object { !$_.Special -and $_.LocalPath })
# Unavailable containers/roaming profiles must not silently disappear from the cleanup report.
@@ -789,30 +758,34 @@ function Invoke-OfficeDeployment {
return [pscustomobject]@{
OfficeDeploymentStatus='ValidationPassed'; ExitCode=0; ValidateBeforeChanges=$true
ProductId=$Options.ProductId; OfficeVersion=$media.Version; Architecture=$Options.OfficeArchitecture
UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams
UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams; OfficeRemovalMethod='SilentODT'; DeferReboot=$Options.DeferReboot
Workspace=$workspace; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps
NextStep='Set ValidateBeforeChanges=false to deploy. That run repeats validation and downloads fresh media.'
}
}
Stop-OfficeDeploymentApps $Options
$reboot = Remove-OfficeCompanionApps $workspace
if ($reboot) {
if ($reboot -and !(Test-OfficeCanDeferRestart $Options 'Companions')) {
$null = Write-Output 'Companion app removal requires a restart. Restart and rerun; Office installation has not started.'
return [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; Workspace = $workspace; PendingUserSids = @() }
return [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'CompanionRemoval'; Workspace = $workspace; PendingUserSids = @() }
}
$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.'
return [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @() }
}
Remove-OfficeSuite $media $workspace
foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile }
$pending = Start-OfficeUserCleanup $profiles $media $workspace
Set-OfficeReinstallPhase $workspace
$code = Install-OfficeMedia $Options $media $workspace
$companions = Install-OfficeCompanionApps $media.Companions $workspace -InstallTeams $Options.InstallTeams
if ($companions.ExitCode -eq 3010) { $code = 3010 }
if ($reboot -or $removalCode -eq 3010 -or $companions.ExitCode -eq 3010) { $code = 3010 }
$status = if ($pending.Count) { 'InstalledWithUserCleanupPending' } else { 'Installed' }
$null = Write-Output "$status. Office $($media.Version), $($Options.ProductId). Restart after the Office scrub is recommended; no automatic reboot was requested."
$null = Write-Output "$status. Office $($media.Version), $($Options.ProductId). No automatic reboot was requested."
$provisionedApps = if ($Options.InstallTeams) { 'Teams and new Outlook are' } else { 'New Outlook is' }
$null = Write-Output "$provisionedApps provisioned for all users; OneDrive is installed per-machine. Users may need to sign out and back in to register the apps."
$null = Write-Output 'Windows work-account/WAM sign-in is preserved; Windows SSO can sign Office in again. App installation does not grant Teams or mailbox entitlements.'
[pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if ($pending.Count -and $code -eq 0) { 2 } else { $code }); ValidateBeforeChanges=$false; Workspace = $workspace; PendingUserSids = $pending; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version }
[pscustomobject]@{ OfficeDeploymentStatus = $status; ExitCode = $(if ($pending.Count -and $code -eq 0) { 2 } else { $code }); RestartRequired=($code -eq 3010); DeferReboot=$Options.DeferReboot; ValidateBeforeChanges=$false; Workspace = $workspace; PendingUserSids = $pending; CompanionApps=$companions.Versions; TeamsSelected=$Options.InstallTeams; ProductId=$Options.ProductId; OfficeVersion=$media.Version }
} finally {
if ($locked) { $mutex.ReleaseMutex() }
$mutex.Dispose()
@@ -868,7 +841,7 @@ function Invoke-OfficeDeploymentEntry {
if ($options.ValidateBeforeChanges) {
Microsoft.PowerShell.Utility\Write-Output 'Validation only: checking prerequisites and staging current installers/Office media (several GB). No app shutdown, cleanup, or installation will run.'
} else {
Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: validating and staging media, then removing and reinstalling Office and the selected companion apps.'
Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: validating and staging media, then silently removing Office with ODT and reinstalling Office and the selected companion apps.'
}
Microsoft.PowerShell.Utility\Write-Output "Diagnostic log: $Global:LogFile"
$results = @(Invoke-OfficeDeployment -Options $options)
@@ -879,13 +852,14 @@ function Invoke-OfficeDeploymentEntry {
$null = Write-Output $receipt
Microsoft.PowerShell.Utility\Write-Output $receipt
if ($deployment[0].OfficeDeploymentStatus -like 'Installed*') {
Microsoft.PowerShell.Utility\Write-Output 'Restart after the Office scrub is recommended. Users may need to sign out and back in for companion app registration; check PendingUserSids for deferred cleanup.'
if ($deployment[0].ExitCode -eq 3010) { Microsoft.PowerShell.Utility\Write-Output 'A restart is required to finish deployment; no automatic reboot was requested.' }
Microsoft.PowerShell.Utility\Write-Output 'Users may need to sign out and back in for companion app registration; check PendingUserSids for deferred cleanup.'
}
$ExitCode.Value = [int]$deployment[0].ExitCode
}
$OfficeInputValues = @{}
foreach ($OfficeInputName in @('OfficeSubscription', 'OfficeArchitecture', 'UpdateChannel', 'OfficeActivation', 'OfficeAppShutdown', 'ValidateBeforeChanges', 'COMPANY')) {
foreach ($OfficeInputName in @('OfficeSubscription', 'OfficeArchitecture', 'UpdateChannel', 'OfficeActivation', 'OfficeAppShutdown', 'DeferReboot', 'ValidateBeforeChanges', 'COMPANY')) {
$OfficeInputVariable = Get-Variable -Name $OfficeInputName -ErrorAction SilentlyContinue
$OfficeInputValues[$OfficeInputName] = if ($null -ne $OfficeInputVariable) { [string]$OfficeInputVariable.Value } else { '' }
}