Files
management-scripts/docs/Office365-Deployment.md

214 lines
48 KiB
Markdown

# Microsoft 365 clean deployment through Syncro
The script defaults to **validation only**. Set `ValidateBeforeChanges=false` explicitly to enable a destructive replacement of the Office installation. Deployment removes the Office suite, Visio, Project, separate Teams installations, OneDrive, and new Outlook, then silently installs the selected Microsoft 365 desktop suite, **new Outlook and OneDrive**, plus **current Teams only when the selected subscription includes Teams**. Classic Outlook is included alongside new Outlook. Visio and Project are not reinstalled. User documents, Outlook PST/OST files, and OneDrive sync folders are not deliberately deleted. Per-user cleanup for absent users has the boundaries described below.
The selection identifies the client's purchased subscription; it does not discover tenant licenses, purchase a license, or assign one. The user still needs a matching assigned license. Windows work-account sign-in is preserved, so Windows SSO can sign Office in again.
## Publish and configure
1. Publish `Install-MicrosoftOffice365.ps1` and `resources/office/Office-UserCleanup.ps1` together in the public repository. The installer requires helper version `EmberkomOfficeUserCleanup-v5`, which runs from memory and uses ProgramData only for synchronization state. The existing `Tools.ps1` is used unchanged. Nothing in this change publishes itself.
2. Paste/upload **rmm/Install-MicrosoftOffice365.ps1** as the Syncro **Windows PowerShell 5.1** script. Select **Run As: System** and set the execution limit to **120 minutes (2 hours)**. PowerShell 7 is not required or launched. Allow enough disk space for both the download and installation. A clean deployment downloads several GB per endpoint and requires internet access throughout companion app installation. Syncro's limit covers the entire run, including downloads, cleanup, and installation.
3. Use **Add Script Variable**, type **Dropdown**, then **Edit Dropdown Values** for each variable below. Enter names without `$`. Syncro stores dropdown definitions separately; uploading a `.ps1` does not create them. See [Syncro's script editor documentation](https://docs.syncrosecure.com/scripting-apis/manage-scripts).
4. First run with `ValidateBeforeChanges=true` and review the result. To deploy, rerun with `false` during the maintenance window. Pilot on a disposable VM with representative Office, user profiles, and companion apps. Then run against the intended endpoint or asset selection. Group endpoints by subscription and architecture so each run's selections apply correctly.
| Variable | Exact dropdown values | Default |
| --- | --- | --- |
| `ValidateBeforeChanges` | `true`, `false` | `true` (validate only; `false` enables removal/reinstallation) |
| `OfficeSubscription` | Use the subscription list below, plus `Select a subscription` | `Select a subscription` (deliberately rejected until changed) |
| `OfficeArchitecture` | `Auto`, `64`, `32` | `Auto` |
| `UpdateChannel` | `Current`, `MonthlyEnterprise`, `SemiAnnual` | `Current` |
| `OfficeActivation` | `User`, `SharedComputer` | `User` |
| `OfficeAppShutdown` | `Abort`, `Force` | `Abort` |
| `DeferReboot` | `true`, `false` | `true` |
All variables configured in Syncro must have a nonempty value. Set the dropdown defaults above in Syncro; the shim reads the injected strings without assigning over them. `Select a subscription` is a nonempty placeholder that the main script rejects before deployment.
`ValidateBeforeChanges` uses the existing `ConvertTo-RmmBoolean` helper from `Tools.ps1`. Missing, null, or blank input defaults to `true`; invalid text fails. The workload requires a parsed Boolean, preventing an omitted or unparsed value from enabling changes. `false` still verifies prerequisites and fresh downloads before removing installed apps.
Syncro supplies `COMPANY` automatically with the endpoint's company name in this environment. Preserve that existing mapping; no company dropdown is needed. The shim passes it through to the main script, which includes `<AppSettings><Setup Name="Company" Value="..." /></AppSettings>` in the ODT configuration, retaining the original installer's company setting. Outside Syncro, a missing value (or `None`) omits this setting. No product key, password, or tenant credentials are needed in Syncro.
`Abort` stops if an Office app, Teams, OneDrive, or new Outlook is running. `Force` closes them across all sessions after staging succeeds; unsaved work can be lost. Choose Force only for the intended maintenance window. Deferred cleanup also closes that user's classic Teams when removing it at sign-in.
`DeferReboot=true` (default) attempts to finish deployment in one run. When an uninstaller returns `3010`, the script waits for removal verification; if the old products are gone, it continues and carries the restart requirement into the final receipt. If removal cannot be verified, it returns `RestartRequiredBeforeInstall` even with `true` selected. `DeferReboot=false` returns that status immediately when an Office or companion uninstaller requests a restart. Neither choice restarts Windows or schedules a reboot. The main script parses the injected string using `ConvertTo-RmmBoolean` from Tools.ps1; missing/null/blank input defaults to `true`, invalid values fail validation, and receipts contain a JSON Boolean. Configure this dropdown in Syncro; the shim still only forwards injected strings through `Run-Script`.
`Auto` selects 64-bit Office on 64-bit Windows and 32-bit otherwise. Select `32` only for required add-in compatibility on supported x86/x64 systems. ARM64 rejects 32-bit Office. Companion installers follow the Windows architecture independently of Office bitness. The main repository script relaunches a 32-bit Syncro host into native Windows PowerShell 5.1 via `Sysnative` on 64-bit Windows, preserving the injected strings. All scheduled user cleanup also uses `powershell.exe`. The RMM shim contains no deployment or relaunch logic.
Before removal, the script checks the apps' minimum OS requirements: Windows build 19041 or newer; Windows Server requires at least 2022 build 20348.2402 for new Outlook. Windows 10 LTSC is rejected when Teams is selected. These checks do not replace checking current Office/Windows support and the additional requirements of an RDS/AVD deployment.
## Subscription choices
Copy these exact names into the `OfficeSubscription` dropdown. The mapping follows [Microsoft's ODT product ID table](https://learn.microsoft.com/en-us/previous-versions/troubleshoot/microsoft-365/microsoft-365-apps/office-suite-problems/product-ids-supported-office-deployment-click-to-run).
| Subscription | ODT product |
| --- | --- |
| 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 |
The E3/E5 selections are consolidated because those plans use the same Office product and shared-computer activation validation. Their other subscription features do not change this installer. The previously documented individual E3/E5 names remain accepted as aliases for saved selections, but only the two combined names are needed in the dropdown. Business Standard and Premium remain separate because their shared-computer activation eligibility differs.
All selections install new Outlook and OneDrive. Teams is downloaded and installed only for `Microsoft 365 Business Standard`, `Microsoft 365 Business Premium`, and `Microsoft/Office 365 E3/E5` (including their accepted legacy enterprise aliases). Every `(no Teams)` selection and both standalone `Microsoft 365 Apps for business` / `Microsoft 365 Apps for enterprise` selections skip the Teams download, installation, and installed-version verification. ODT also explicitly excludes Teams, so it cannot bypass this selection. Existing Teams installations are still removed during cleanup. Installing a client does not purchase/assign service entitlements; users must have the appropriate account and services to use it.
Business Basic, E1, frontline/web-only plans, education/government variants, consumer subscriptions, and perpetual Office/LTSC editions are not deployment selections in this script. Missing or unsupported selections stop before downloads or removal. Existing perpetual Click-to-Run installations, including retail Office 2019/2021, are targeted by ODT's removal pass; supported older MSI editions are removed during installation as described below. That does not authorize installing Microsoft 365 without its license.
`SharedComputer` enables shared computer activation. Business Standard and standalone Apps for business are rejected for this mode; Business Premium and the listed eligible enterprise plans are accepted. Confirm the users' entitlements and host support, especially on RDS/AVD. See [Microsoft's shared activation requirements](https://learn.microsoft.com/en-us/microsoft-365-apps/licensing-activation/overview-shared-computer-activation).
## Download, removal, and installation
With `ValidateBeforeChanges=true`, the script checks the subscription/activation combination, host and OS prerequisites, running apps, registered profile availability, free space, writable paths, and HTTP availability. It returns `ValidationPassed` with the deployment plan, existing Office inventory, Click-to-Run state, running apps, `WritablePaths` and `DownloadChecks`. It creates no deployment directory and downloads no response bodies, release metadata or installation files. It does not clean old artifacts, close apps, uninstall, clear credentials, register tasks, or install apps. `OfficeAppShutdown=Force` only reports running apps; `Abort` fails if any are running.
Assessment sends HTTP HEAD requests, follows redirects, and requires status 200 for the ODT discovery page, helper, conditional Get Help recovery download, selected channel's Office CDN manifest, selected companion installer links, and Windows 10 release-history page when applicable. A refused HEAD request fails assessment; there is no GET fallback. The current versioned ODT executable URL and exact Windows 10 build require reading metadata, so those are resolved only in deployment mode. `OfficeVersion` is empty, `MetadataResolved=false`, `Workspace` is null and `MediaDownloaded=false`. HEAD success does not prove payload integrity, future installation or activation. The normal Tools/core bootstrap still loads live, and the normal Tools log is written. Writable-path checks create a zero-byte delete-on-close probe in the nearest existing parent of staging, ProgramData state, and Program Files paths; they leave no probe or deployment folder behind.
With `ValidateBeforeChanges=false`, the script checks prerequisites, retires previous idle user cleanup tasks, removes previous deployment artifacts while preserving logs, checks available space, and creates a fresh protected workspace. It downloads and verifies the full Office payload and selected bootstrappers, rechecks free space and running apps, performs removal/installation, verifies results, and removes all non-log staging files in `finally`. Download failures occur before installed apps are removed. An active prior installer/task or unsafe/locked artifact stops preparation; cached content is never a fallback.
Disk-space checks reserve **10 GB for installation and companion apps**, plus **6 GB for a fresh media download** on the staging drive. When staging, Windows, and Program Files share C:, validation and initial deployment checks require 16 GB free; installation also requires 10 GB remaining after staging. Separate installation volumes are checked independently. These are adjustable headroom values in `Get-OfficeDeploymentDefinitions`, not Microsoft's minimum requirements or a guarantee against concurrent disk use. Low space fails before app removal. Deployment clears prior staging before this check; assessment never performs housekeeping.
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.
**ODT remains the normal removal path. Get Help is downloaded and run only for conditional recovery.** The command-line scrub is noninteractive, but it is not guaranteed to be invisible: the Get Help build observed on October 14, 2026 created an elevated PowerShell cleanup window in the logged-in user's session even with a hidden SYSTEM parent. Microsoft's documented `-HideProgress` option applies to other scenarios, not Office removal, so the script does not add it. See the [Get Help command-line reference](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-command-line-overview). Normal successful deployments and assessment runs do not download the scrubber.
On Windows 11, the download and installation XML omit `Version`, letting ODT select the latest available build in the selected channel. ODT may fetch newer files at installation time if the channel advances during the run. Verification accepts the staged build or a newer build and reports the actual installed version. There is no fixed build number to maintain.
Windows 10 is the exception: Microsoft limits it to [Office feature release 2608 with subsequent security updates](https://learn.microsoft.com/en-us/microsoft-365-apps/end-of-support/windows-10-support). In deployment mode, before downloading installers or removing apps, the script resolves the highest published 2608 build for the selected channel from [Microsoft's release history](https://learn.microsoft.com/en-us/officeupdates/update-history-microsoft365-apps-by-date). Only Windows 10 specifies that build in the download/install XML. Missing release data or a mismatched download stops before removal. The feature release and history/channel definitions are centralized at the top of the script; patch build numbers are not hardcoded. Server editions are not classified as Windows 10 by their build number.
Installation uses English (`en-us`), enables updates, and uses `Display Level="None"`. No `Updates TargetVersion` is set, so installation selection does not freeze future updates. 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.
The companion apps remain excluded from ODT because the main script installs the selected companions explicitly for all users after Office. Their installers are downloaded from Microsoft's evergreen links and their Microsoft Authenticode signatures checked before any removal; Teams is staged only when the subscription includes it. Teams, new Outlook, and WebView2 use online bootstrappers: only their installer executables are staged, and their payload downloads can still fail later. The complete Office suite payload is staged before removal.
| Component | Silent deployment | Verification |
| --- | --- | --- |
| WebView2 runtime, if missing machine-wide | `MicrosoftEdgeWebview2Setup.exe /silent /install` | Machine runtime version registration |
| OneDrive | `OneDriveSetup.exe /allusers /silent` | Machine version registration and Microsoft-signed executable under Program Files |
| Teams, when included in the subscription | `teamsbootstrapper.exe -p` | `MSTeams` provisioned package |
| New Outlook | `OutlookSetup.exe --provision true --quiet --start-` | `Microsoft.OutlookForWindows` provisioned package |
These follow Microsoft's deployment guidance for [Teams](https://learn.microsoft.com/en-us/microsoftteams/teams-client-bulk-install), [new Outlook](https://learn.microsoft.com/en-us/microsoft-365-apps/outlook/get-started/deployment-new-outlook), [OneDrive per-machine installation](https://learn.microsoft.com/en-us/sharepoint/per-machine-installation), and [WebView2](https://learn.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution). Although the Outlook instructions show a PowerShell 7 shell, the command invokes a native executable; this script passes its arguments through `Start-Process` in Windows PowerShell 5.1. No `pwsh`, winget, or interactive Store sign-in is used. The existing evergreen WebView2 runtime, when present, retains its normal update mechanism.
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.
Teams now uses a [unified app for work, school, and personal accounts](https://techcommunity.microsoft.com/blog/microsoftteamsblog/unified-teams-app-for-work-personal-and-education-accounts-is-now-available-on-a/4217988). `teamsbootstrapper.exe -p` is Microsoft's business deployment method; verification requires the Microsoft-published `MSTeams` package and logs its package identity. The old personal-only `MicrosoftTeams` package does not satisfy that check. Users should add/select their licensed work or school account; a personal account can show the Teams Free experience in the same unified app. The script does not choose a Teams account or change sign-in policy.
A window that offers **Get Microsoft Teams (work or school)** does not by itself identify the installed package. Check the running executable path: `WindowsApps\MSTeams_<version>\ms-teams.exe` identifies the current client; do not attribute that window to an older personal-client process. Microsoft [documents support for personal and work/school accounts in the downloaded app](https://support.microsoft.com/en-us/teams/platform/how-do-i-get-microsoft-teams). Test **Create or use another account** with the licensed work account and record any actual sign-in error before changing deployment or sign-in policy. Machine provisioning alone does not prove a user's work-account sign-in succeeds.
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. 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 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.
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`, 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.
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.
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 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.
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).
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.
Native installer processes, including ODT and the conditional scrub, are awaited using `Start-Process -Wait`; there is no separate 30-minute installer cutoff. Get Help can detach a worker beyond that wait, as described above. Syncro's two-hour limit remains the overall limit and is not reset between phases. After a terminal scrub result, verification allows five minutes for registration and background-worker state to settle. Surviving Get Help/OffScrub workers, including `GetHelpElevated\...\Run.ps1`, block installation, new deployment downloads, and artifact deletion even outside the current workspace. Waiting for active user cleanup and its reinstall-transition lock allows 20 minutes; the per-user scheduled task limit is 30 minutes. Those tasks may also run later for absent users. These allowances do not guarantee every endpoint finishes within two hours. If the RMM terminates a run, check for surviving installer processes before rerunning; the script does not kill an active installer to meet a time budget.
Transient failures get bounded recovery before deployment stops:
- HTTP downloads, including the ODT discovery page, get three attempts. Recoverable failures and successful retries are recorded in the Tools diagnostic log with the URL and destination, without emitting errors to Syncro. If all attempts fail, the final error identifies the URL, destination, attempt count, and last failure. 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.
- Direct machine and per-user companion 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. This retry applies to `msiexec.exe`, not ODT's internal `RemoveMSI` operation. The script does not kill an unrelated installer or blindly repeat an Office removal or installation.
- After successful operations, machine removal and installation verification allow up to five minutes of polling for registry/package state to settle. The standalone user's Teams add-in verification retains its 60-second allowance. 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.
- Failure to create/register a user's cleanup task is logged with its SID, profile path, and error, then scheduling continues for the remaining profiles and Office installation proceeds. This handles stale profiles whose accounts no longer resolve, without assuming that every unresolved account has been deleted. Registration failures remain visible in the receipt and are not described as tasks waiting for sign-in. Active cleanup and its transition lock must still finish before installation to prevent concurrent uninstall/install operations.
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
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.
Credential Manager belongs to each user. A limited-privilege scheduled task clears Office-prefixed credentials and removes per-user classic Teams. Before reinstallation begins, it also removes the user's old Teams meeting add-in and OneDrive. It runs immediately where a user session is available; otherwise it runs at that user's next sign-in. No passwords are stored. These tasks are named `Emberkom-OfficeCleanup-<deployment-id>-<SID>`.
An HKLM uninstall entry does not always mean the Teams meeting add-in is installed per-machine. The main script checks its actual machine registration through the read-only Windows Installer API before attempting a SYSTEM uninstall. The user helper checks both HKCU and HKLM uninstall entries, then selects only add-in products registered for that user. Removal is verified against that user's MSI registration, so another user's or a leftover display entry cannot cause a false failure. MSI query errors stop cleanup; the script does not delete uninstall registry keys to bypass verification. See [Microsoft's installation context enumeration API](https://learn.microsoft.com/en-us/windows/win32/api/msi/nf-msi-msienumproductsexw).
A file lock serializes user uninstallers with the transition to reinstallation. Once the protected `reinstall-started` marker is written, later user tasks preserve the Teams meeting add-in and OneDrive so they cannot uninstall the newly deployed apps. For absent users, OneDrive's per-machine installer handles migration; an existing per-user Teams meeting add-in can remain even when the Teams client is not reinstalled. Cleanup completion does not mean that every old per-user companion artifact was purged. Office credentials and classic Teams are still cleaned on the next sign-in.
Windows work/school registration, WAM/AAD BrokerPlugin, generic Windows credentials, and device enrollment are preserved. This intentionally does not remove every Microsoft sign-in token. Microsoft's [activation reset guide](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365-apps/activation/reset-activation-state) distinguishes Office caches from shared WAM and workplace registration state.
A deployment is reported as **InstalledWithUserCleanupPending** if any user task has not completed. Failed tasks also remain pending and retry on later sign-ins. The helper writes `Status=Complete` under `HKCU\Software\Emberkom\OfficeDeployment\<deployment-id>` after success and then becomes a no-op. Tasks completed during deployment are removed automatically. Tasks that finish later remain registered but do no cleanup after success. An administrator can confirm completion and remove those exact tasks and their synchronization folder afterward. There is no daily housekeeping task.
If any cleanup task could not be registered, successful installation instead returns **InstalledWithUserCleanupIncomplete** with `UserCleanupRegistrationFailures` entries containing `SID`, `ProfilePath`, and `Error`. `PendingUserSids` still lists only registered tasks awaiting completion. Signing in alone cannot retry a missing task: review whether the profile belongs to a deleted account or whether account lookup/task registration needs repair. The script does not delete profiles or grant a different account access to their credentials. The machine-side Office identity/cache cleanup still runs before task registration.
These logon tasks fetch the version-matched user helper live over HTTPS and execute it in memory; sign-in cleanup therefore requires network access to the repository. No helper script or installer is cached for them. Only the empty lock and reinstall-phase marker remain in `%ProgramData%\EmberkomOfficeDeployment\<deployment-id>` while tasks are pending. These are required synchronization state, separate from the logs-only download workspace. The receipt identifies this folder as `UserCleanupWorkspace`. If no tasks remain after a successful deployment, the folder is removed too. A new deployment retires previous idle tasks and clears their state before creating fresh tasks for the currently registered profiles; active tasks block redeployment. If preparation then fails, the retired tasks are not recreated until deployment reaches user cleanup again.
## Temporary media and cleanup during deployment
- Each actual installation uses a fresh protected `EmberkomOfficeDeployment\<deployment-id>` directory in the execution account's `[IO.Path]::GetTempPath()`. Under SYSTEM this can be `C:\Windows\SystemTemp`. There is no cross-run reuse of media, manifests, options or XML.
- Before creating it, deployment cleans prior GUID workspaces under execution/profile temp, Windows Temp/SystemTemp and legacy ProgramData roots. There is no minimum age. Non-GUID folders outside this managed scope are untouched.
- `finally` removes every non-log file from the current download workspace on success, failed download/install, and early restart exits. This includes payloads, bootstrappers, helper scripts, XML, options and locks. `.log` and `.etl` files and their parent directories remain. The selected options are recorded in `deployment-options.log`.
- Before deleting artifacts, cleanup rejects reparse points, inventories processes, and probes all candidate files for exclusive access. Active installers or processes referencing the workspace block cleanup. Process-inventory failures also retain the files. A new deployment stops if prior artifacts cannot be cleared safely.
- Receipts include `ArtifactCleanupPending=true` when cleanup fails. An otherwise clean install then returns exit `2` and `InstalledWithArtifactCleanupPending`; existing errors, partial-user-cleanup statuses and required-restart results remain intact. The original installation exception is never replaced by a cleanup error.
- Pending logon tasks retain only their separate synchronization state, as described above. No downloaded code or media is intentionally retained for them.
- Hard RMM termination or power loss can bypass `finally`. The next deployment clears the abandoned artifacts before downloading anything new. No scheduled housekeeping job is created. `Start-SystemCleanup.ps1` retains its separate conservative, age-based cleanup behavior for legacy workspaces; it is not required before redeployment.
## Results and troubleshooting
| Caller exit code | Meaning |
| --- | --- |
| `0` | `ValidationPassed`: validation only, no deployment performed. `Installed`: Office and companion installations verified; user cleanup completed for the enumerated profiles. |
| `1` | Failure; inspect the error and logs. In deployment mode, removal may already have happened. |
| `2` | Installation completed with pending work: `InstalledWithUserCleanupPending` lists users needing sign-in; `InstalledWithUserCleanupIncomplete` lists task-registration failures; `InstalledWithArtifactCleanupPending` indicates artifacts could not be removed safely. Inspect the receipt and logs. Do not repeatedly reinstall merely to check status. |
| `3010` | A restart is required. Read `OfficeDeploymentStatus`: `RestartRequiredBeforeInstall` means restart then rerun; any `Installed*` status means Office and companions completed with a restart deferred until afterward. `RestartRequired=true` and `DeferReboot` are included; a stop before installation also identifies `RestartStage`. Pending user SIDs and task registration failures can also be present. |
Syncro may flag nonzero results as errors; read the printed status, pending SIDs, and task registration failures. Schedule any required restart separately. The script also returns `3010` after verified legacy MSI Office removal, following Microsoft's restart requirement.
ODT's redirected `stdout`/`stderr` files can be empty even when installation fails. Microsoft writes native setup/Click-to-Run logs in the execution account's temp directory and `C:\Windows\Temp`; SYSTEM's temp may be `C:\Windows\SystemTemp`. On an ODT failure, the script searches those folders for recent, nonempty Office/setup or computer-name logs and appends bounded error excerpts and their full paths to the existing Tools diagnostic log. Look for `Native Office log:` and `Native Office detail:`. Collection is read-only, creates no task or additional resident helper, and cannot override the original installer exit code. Excerpts are clues; retain the full native logs when diagnosing a failure.
Exit `17004` is documented as `ERROR_COMPLETING_SCENARIO_NEED_CLEAN_UP`, with possible reasons including unknown SKUs or unavailable CDN content. It does not establish that an old Office installation needs a scrub. Inspect the native error details before changing removal behavior or repeating a destructive deployment. See [Microsoft's Office CSP error table](https://learn.microsoft.com/en-us/windows/client-management/mdm/office-csp) and [ODT troubleshooting log locations](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/deploy-microsoft-365-apps-local-source).
If machine companion removal still fails verification, the error identifies the remaining component, version, and registry location, along with the uninstall log folder. The main log also records which add-in registrations were left to user cleanup. An uninstall exit code of `1605` alone does not establish that all users' installations are gone; Windows Installer context determines which stage handles the add-in. This failure occurs before Office removal, identity reset, and reinstallation, but companion apps may already have been removed.
The main script uses the overridden `Write-Output` and `Write-Error` from `Tools.ps1` for actions, retries, failures, and the final receipt, writing to its existing `$Global:LogFile`. Internal action messages suppress the logger's echoed success output to keep function results separate from diagnostics. The mode notice, log location, and final receipt use `Microsoft.PowerShell.Utility\Write-Output` for Syncro. Errors are logged and also printed to Syncro. Native PowerShell relaunch reloads Tools and restores the caller's log path. Run the core through the shim/Tools execution context, not as an independent file without Tools.
Process stdout/stderr logs and `deployment-options.log` remain in the reported `Workspace`. Generated `remove.xml` and `install.xml` are deleted along with downloaded content after each attempt; assessment creates no workspace. ODT removal logs are `office-remove.stdout.log` / `.stderr.log`; installation logs are `office-install.stdout.log` / `.stderr.log`. The main Tools log retains the actions, results, and receipt and is not deleted. The separate limited-user cleanup task writes its transcript in `%LOCALAPPDATA%\Emberkom\OfficeDeployment\<deployment-id>.log`. Do not manually delete `UserCleanupWorkspace` synchronization state while its logon tasks are pending.
The separate legacy `Uninstall-MicrosoftOffice.ps1` deletes its downloaded VBS in `finally`, including after a failed/partial download or launch error. It is not part of the modern installer workflow. Registry-only Office fixes do not stage installers, and RMM shims execute their downloaded PowerShell source in memory.
The installer verifies the selected Office product, bitness, and downloaded version in Click-to-Run registration, plus selected companion deployment as listed above. The final receipt includes `CompanionApps` versions and `TeamsSelected`; when Teams is skipped, it has no installed version in that receipt. Any selected companion installer or verification failure fails the deployment, even if Office installed successfully. It does not claim that the subscription has activated. It does not delete mail profiles, revoke cloud sessions, or roll back a removed Office installation.
## Verification
Run `powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\tests\Install-MicrosoftOffice365.Tests.ps1` for offline checks in Windows PowerShell 5.1. Coverage includes HEAD-only assessment and status failures, temporary write probes, no metadata/staging/housekeeping during assessment, prior-run cleanup with nested-log preservation, active-process/task and locked-file protection, live user-helper execution, orphaned Click-to-Run removal and stale-state rejection. Recovery checks cover the observed InvalidDirectory error, exclusion of stale/unrelated evidence, ZIP containment, signature failures, one-attempt enforcement, ambiguous/failed/not-found scrub results, zero-exit argument/usage errors, bounded stream excerpts without changing parser input, surviving workers, all-product removal verification, log preservation and both restart policies. Existing checks cover strings through the real shim/Tools loader, exit-code propagation, native-host relaunch, deployment order, companion verification, retries and identity cleanup boundaries. Tests mock downloads and disruptive actions; they do not run Microsoft installers, change actual registry state, or clear 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.
Restored scrub tests cover advertised/unsupported arguments, both result formats, background acknowledgement, delayed inventory, a restarted quiet interval, a worker left at the keypress prompt, closed/failed workers, unknown worker identity, missing observed workers, stale state, and the 30-minute bound. An inert PowerShell child verifies that the retained process handle preserves a nonzero exit code after the child terminates. No actual scrubber is executed by the suite.
Endpoint acceptance still requires a VM pilot: existing MSI/C2R/Store Office, machine/per-user Teams and OneDrive, a logged-off profile, standard-user sign-in, wrong-license rejection, download failure, and the restart path. Verify new Outlook and Teams registration at sign-in, OneDrive migration, and that delayed cleanup preserves reinstalled apps. The implementation has not been run destructively against a real endpoint during development.
## Maintaining deployment definitions
`Get-OfficeDeploymentDefinitions` at the top of the main script groups subscription/product mappings, Teams and shared activation eligibility, allowed dropdown choices, download URLs/discovery patterns, installer arguments and package identities, language/build checks, OS minimums, cleanup targets, and timeouts. There is no additional configuration file. Review these contracts when Microsoft changes licensing, packaging, platform support, or cleanup behavior; evergreen downloads avoid routine version-number updates. Keep the Syncro dropdown definitions and this guide aligned when changing allowed selections. The limited-user helper retains its own scoped cleanup logic and version marker; changes to that contract require publishing both scripts together.