#Requires -Version 5.1 <# Validates by default; destructive clean deployment requires ValidateBeforeChanges=false. Run elevated in Windows PowerShell 5.1 with Tools.ps1 loaded. Inputs are inherited from the RMM caller; no script-level param block. See docs/Office365-Deployment.md for Syncro dropdowns and cleanup boundaries. #> function Get-OfficeDeploymentDefinitions { # Maintenance surface: edit Microsoft's deployment contracts here, not a separate file. # Evergreen URLs avoid pinning installer releases. Product/license mappings remain explicit. @{ Plans = @{ 'Microsoft 365 Business Standard' = 'O365BusinessRetail' 'Microsoft 365 Business Premium' = 'O365BusinessRetail' 'Microsoft 365 Apps for business' = 'O365BusinessEEANoTeamsRetail' 'Microsoft 365 Business Standard (no Teams)' = 'O365BusinessEEANoTeamsRetail' 'Microsoft 365 Business Premium (no Teams)' = 'O365BusinessEEANoTeamsRetail' 'Microsoft 365 Apps for enterprise' = 'O365ProPlusEEANoTeamsRetail' 'Microsoft/Office 365 E3/E5' = 'O365ProPlusRetail' 'Microsoft/Office 365 E3/E5 (no Teams)' = 'O365ProPlusEEANoTeamsRetail' } TeamsProducts = @('O365BusinessRetail', 'O365ProPlusRetail') SharedComputerBusinessPlans = @('Microsoft 365 Business Premium', 'Microsoft 365 Business Premium (no Teams)') Choices = @{ OfficeArchitecture = @('Auto', '64', '32') UpdateChannel = @('Current', 'MonthlyEnterprise', 'SemiAnnual') OfficeActivation = @('User', 'SharedComputer') OfficeAppShutdown = @('Abort', 'Force') } 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' 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' # Probe each fresh download's usage; add OfficeVersion only when advertised. ScrubArguments = '-S OfficeScrubScenario -AcceptEula' ScrubAllVersionsArgument = '-OfficeVersion All' ScrubHelpPattern = '(?im)^\s*GetHelpCmd\.exe\s+-S\s+OfficeScrubScenario\s+-AcceptEula(?:\s|$)' ScrubVersionSwitchPattern = '(?im)^\s*-OfficeVersion\b' 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', 'GetHelpCmd.exe', 'SaRAcmd.exe') ScrubRecoveryExitCodes = @(17002, 17004) ScrubDiagnosticLineLimit = 20 ScrubDiagnosticLineCharacters = 2000 HelperVersion = 'EmberkomOfficeUserCleanup-v5' Language = 'en-us' OfficeBuildPattern = '^16\.0\.\d+\.\d+$' OdtExcludedApps = @('Groove', 'OneDrive', 'Lync', 'Teams', 'OutlookForWindows') CompanionInstallers = @{ WebView2 = @{ File='MicrosoftEdgeWebview2Setup.exe'; Uri='https://go.microsoft.com/fwlink/p/?LinkId=2124703'; Arguments='/silent /install' } Teams = @{ File='teamsbootstrapper.exe'; Uri='https://go.microsoft.com/fwlink/?linkid=2243204&clcid=0x409'; Arguments='-p'; Package='MSTeams' } NewOutlook = @{ File='OutlookSetup.exe'; Uri='https://go.microsoft.com/fwlink/?linkid=2207851'; Arguments='--provision true --quiet --start-'; Package='Microsoft.OutlookForWindows' } OneDrive = @{ File='OneDriveSetup.exe'; Arguments='/allusers /silent'; Uris=@{ ARM64='https://go.microsoft.com/fwlink/?linkid=2282608' x64='https://go.microsoft.com/fwlink/?linkid=844652' x86='https://go.microsoft.com/fwlink/?linkid=2181213' } } } WebViewClientId = '{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' AppxPublisherSuffix = '_8wekyb3d8bbwe' MinimumWindowsBuild = 19041 MinimumServerBuild = 20348 MinimumServerRevision = 2402 Windows11Build = 22000 # Windows 10 stays on this feature release; resolve its latest published build # per channel at run time rather than maintaining a fixed patch/build number. Windows10OfficeRelease = '2608' OfficeReleaseHistory = 'https://learn.microsoft.com/en-us/officeupdates/update-history-microsoft365-apps-by-date' OfficeReleaseHistoryChannels = @{ Current = 'current-channel' MonthlyEnterprise = 'monthly-enterprise-channel' SemiAnnual = 'semi-annual-enterprise-channel' } OfficeCdnChannels = @{ Current = '492350f6-3a01-4f97-b9c0-c7c6ddf67d60' MonthlyEnterprise = '55336b82-a18d-4dd6-b5f6-9e5095c314a6' SemiAnnual = '7ffbc6bf-bc32-4f92-8982-f9dd17fd3114' } TeamsUnsupportedWindows10Editions = @('EnterpriseS', 'EnterpriseSN', 'IoTEnterpriseS') # Teams.exe is classic, msteams.exe is the older personal/Windows Chat client, # and ms-teams.exe is the current client. Check all three before removal. RunningAppNames = @('lync', 'winword', 'excel', 'msaccess', 'mstore', 'infopath', 'setlang', 'msouc', 'ois', 'onenote', 'outlook', 'powerpnt', 'mspub', 'groove', 'visio', 'winproj', 'graph', 'teams', 'msteams', 'ms-teams', 'OneDrive', 'olk') AppxRemovalNames = @('Microsoft.Office.Desktop', 'Microsoft.MicrosoftOfficeHub', 'Microsoft.Office.OneNote', 'Microsoft.OutlookForWindows', 'MSTeams', 'MicrosoftTeams') TeamsMsiNames = @('Teams Machine-Wide Installer', 'Microsoft Teams Meeting Add-in for Microsoft Office') OfficeIdentityVersions = @('15.0', '16.0') OfficeIdentityKeys = @('Identity', 'Licensing') OfficeCachePaths = @('AppData\Local\Microsoft\Office\Licenses', 'AppData\Local\Microsoft\Office\16.0\Licensing', 'AppData\Local\Microsoft\Office\15.0\Licensing') DownloadAttempts = 3 DownloadTimeoutSeconds = 300 DownloadRetrySeconds = 3 OdtPageTimeoutSeconds = 120 MsiBusyAttempts = 5 MsiBusyRetrySeconds = 15 # 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 = 20 UserCleanupTaskMinutes = 30 # Deployment headroom, not Microsoft's published minimum system requirements. # Reserve installation/companion space in addition to a fresh media download. MinimumInstallFreeSpaceGB = 10 MediaDownloadReserveGB = 6 SetupDiagnosticFileLimit = 8 SetupDiagnosticTailLines = 2000 SetupDiagnosticErrorLines = 12 } } function Get-OfficeDeploymentOptions { param([hashtable]$InputValues) $definitions = Get-OfficeDeploymentDefinitions $plans = $definitions.Plans # ConvertTo-RmmBoolean treats blank as false; this destructive workflow must default to true. [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. if ($subscription -match '^(Microsoft|Office) 365 E[35]( \(no Teams\))?$') { $subscription = 'Microsoft/Office 365 E3/E5' + $Matches[2] } if (!$plans.ContainsKey($subscription)) { throw "Select a supported OfficeSubscription. '$subscription' is not supported. Business Basic, E1, and frontline/web-only plans do not license this desktop suite." } $choices = $definitions.Choices [string]$company = $InputValues.COMPANY $company = $company.Trim() if ($company -eq 'None') { $company = '' } $options = @{ OfficeSubscription = $subscription; ProductId = $plans[$subscription]; Company = $company; ValidateBeforeChanges = $validateOnly; DeferReboot = $deferReboot } # Internal values, populated from the host and Microsoft's release history, not RMM input. $options.OfficeFeatureRelease = ''; $options.TargetOfficeVersion = '' # 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) { [string]$value = $InputValues[$name] $value = $value.Trim() if (!$value) { $value = $choices[$name][0] } if ($value -notin $choices[$name]) { throw "Invalid ${name}: '$value'. Allowed: $($choices[$name] -join ', ')." } $options[$name] = $value } if ($options.OfficeActivation -eq 'SharedComputer' -and $options.ProductId -like 'O365Business*' -and $subscription -notin $definitions.SharedComputerBusinessPlans) { throw 'Shared computer activation requires Business Premium or an eligible enterprise subscription.' } if ($options.OfficeArchitecture -eq 'Auto') { $options.OfficeArchitecture = if ([Environment]::Is64BitOperatingSystem) { '64' } else { '32' } } if ($options.OfficeArchitecture -eq '64' -and ![Environment]::Is64BitOperatingSystem) { throw '64-bit Office requires 64-bit Windows.' } if ($options.OfficeArchitecture -eq '32' -and ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64' -or $env:PROCESSOR_ARCHITEW6432 -eq 'ARM64')) { throw '32-bit Office is not supported on Windows ARM64.' } [pscustomobject]$options } function Assert-OfficeDeploymentHost { param($Options) $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) if (!$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Office deployment requires SYSTEM or an elevated administrator.' } if ([Environment]::Is64BitOperatingSystem -and ![Environment]::Is64BitProcess) { throw 'Office deployment must run in native Windows PowerShell; the main script entry point handles relaunch.' } if ($PSVersionTable.PSEdition -ne 'Desktop' -or $PSVersionTable.PSVersion.Major -ne 5 -or $PSVersionTable.PSVersion.Minor -ne 1) { throw 'Run in Windows PowerShell 5.1 for Appx support.' } foreach ($command in @('Get-AppxPackage', 'Remove-AppxPackage', 'Get-AppxProvisionedPackage', 'Remove-AppxProvisionedPackage', 'Register-ScheduledTask')) { $null = Get-Command $command -ErrorAction Stop } $os = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop $windows = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction Stop Assert-OfficeCompanionPlatform -Build ([int]$os.BuildNumber) -ProductType ([int]$os.ProductType) -Revision ([int]$windows.UBR) -EditionId $windows.EditionID -InstallTeams $Options.InstallTeams $Options.OfficeFeatureRelease = Get-OfficeFeatureRelease -Build ([int]$os.BuildNumber) -ProductType ([int]$os.ProductType) $null = Write-Output "Deployment host: $($os.Caption), build $($os.BuildNumber).$($windows.UBR)." } function Get-OfficeFeatureRelease { param([int]$Build, [int]$ProductType) $definitions = Get-OfficeDeploymentDefinitions if ($ProductType -eq 1 -and $Build -ge $definitions.MinimumWindowsBuild -and $Build -lt $definitions.Windows11Build) { return $definitions.Windows10OfficeRelease } return '' } function Get-OfficeBuildFromHistory { param([string]$PageContent, [string]$UpdateChannel, [string]$FeatureRelease) $definitions = Get-OfficeDeploymentDefinitions $article = $definitions.OfficeReleaseHistoryChannels[$UpdateChannel] if (!$article -or $FeatureRelease -notmatch '^\d{4}$') { throw 'Invalid Office release-history selection.' } $linkPattern = '(^|/)' + [regex]::Escape($article) + '#version-' + $FeatureRelease + '(?:-|$)' $labelPattern = '^\s*Version\s+' + $FeatureRelease + '\s+\(Build\s+(?\d+\.\d+)\)\s*$' $content = [Net.WebUtility]::HtmlDecode($PageContent) $builds = @(foreach ($link in [regex]::Matches($content, ']*\bhref\s*=\s*["''](?[^"'']+)["''][^>]*>(?