# 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-v4`, which handles per-user Teams add-ins advertised in HKLM and protects reinstalled apps from deferred cleanup. 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 performs prerequisite and download validation before cleanup. It does not skip those checks.
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 `` 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, and availability of registered user profiles. It downloads and verifies ODT, the user cleanup helper, the full Office payload, and the selected companion bootstrappers. It writes the installation/removal XML and options, and returns `ValidationPassed` with `OfficeRemovalMethod=SilentODT`, the selected product, version, company, Teams choice, existing Office inventory, and running apps. It does **not** close apps, uninstall, clear identity/credentials, load user hives, register per-user cleanup tasks, or install apps. `OfficeAppShutdown=Force` only reports running apps in this mode; `Abort` fails validation if any are running.
Validation writes logs and staging files in the execution account's temp directory, secures its workspace, and runs ODT extraction and `/download` when no reusable cache exists; it is not a zero-write inventory scan. Allow several GB for the first run. It registers no scheduled tasks. A later `false` run repeats prerequisites and reuses matching, unexpired media after verifying its SHA-256 hashes and Microsoft executable signatures. The small user cleanup helper is always refreshed from the repository and is deleted from the validation workspace before returning. Validation does not prove tenant entitlements, successful future uninstallation/activation, or availability of the online companion payloads at install time.
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.
**Unattended deployment does not download or launch Get Help.** The Get Help build observed on October 14, 2026 created an elevated PowerShell cleanup window in the logged-in user's session even when its parent ran hidden under SYSTEM. Hiding the parent did not hide that child, and Microsoft's documented `-HideProgress` option applies to other scenarios, not Office removal. See the [Get Help command-line reference](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-command-line-overview). The script uses ODT's supported silent removal instead; an interactive scrub is an attended troubleshooting step only.
On a cache miss, ODT downloads the current build in the selected channel. A cache hit uses the build validated earlier, for at most seven days from the original download; it does not check for a newer build during that interval. Installation is pinned to that local build, uses English (`en-us`), enables updates, and uses `Display Level="None"`. The [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options) describes these settings. Existing update policies can subsequently override the chosen channel.
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_\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. ODT then runs `setup.exe /configure remove.xml` with `` and `` to remove Click-to-Run Office, Visio, and Project without installation UI. 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. It skips this separate pass when only MSI Office, or no Office, is detected. See the [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options).
Legacy MSI Office is handled by `` 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.
This is a supported uninstall and reinstall with our targeted Office identity cleanup, rather than a deep scrub of every Office artifact. A failed ODT removal or remaining non-MSI Office stops before replacement installation; remaining MSI Office after `RemoveMSI` fails the deployment even if the new suite has already installed. The error reports the remaining products and links to [Microsoft's attended scrub guidance](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall). Get Help is never an automatic fallback. Corrupt, unsupported, orphaned, or unusually packaged installations may require that repair. A removal restart result follows `DeferReboot` as described above; no automatic reboot or resume task is created. A deployment already running an older script continues using that downloaded code: let it finish before starting a new deployment.
The former Get Help 30-minute background-wait cutoff has been removed with the scrubber. Native installer processes, including ODT download/removal/installation, are awaited until they exit; there is no separate 30-minute installer cutoff. Syncro's two-hour limit remains the overall limit and is not reset between phases. Main-script registration checks now allow five minutes instead of one. Waiting for active user cleanup and its reinstall-transition lock allows 20 minutes instead of five; the per-user scheduled task limit is 30 minutes instead of 15. Those tasks may also run later for absent users. These allowances improve tolerance for slow operations but 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`.
## 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--`.
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\` after success and then becomes a no-op. Tasks completed during deployment are removed automatically. Tasks that finish later retain their previous behavior: they remain registered but do no further work after success. An administrator can confirm completion and remove those exact tasks and their helper 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.
The helper, lock, and reinstall marker for these previously agreed logon tasks live separately in `%ProgramData%\EmberkomOfficeDeployment\`, so routine temp cleanup cannot break deferred user cleanup. The receipt identifies this folder as `UserCleanupWorkspace`. If no user tasks remain at the end of a successful deployment, the script removes this helper folder too. It is the only deployment code intentionally retained for pending users; the main installer does not persist on the endpoint.
## Temporary media and cleanup during deployment
- A completed staging pass records a protected `media-cache.json` inventory with file hashes, version, original creation time, and a matching key derived from product, architecture, channel, language, and companion download definitions. Compatible runs move these installers into their new workspace instead of copying or redownloading them. This keeps each deployment's user cleanup ID separate. Company, activation, shutdown, and reboot selections are applied to freshly generated XML. The receipt reports `CachedMediaReused`.
- Downloads live under `EmberkomOfficeDeployment\` in `[IO.Path]::GetTempPath()` for the execution account. In Syncro this is SYSTEM's temp location, not the signed-in user's temp directory. The actual path is reported in `Workspace`. Folder permissions prevent standard users from changing executable content.
- Cached installers remain eligible for reuse for **seven days**, provided the files still exist. This is a freshness limit, not a scheduled deletion policy. Expired, incomplete, modified, unsigned, or incompatible caches are not reused. Changing to a no-Teams plan cannot reuse a Teams-enabled cache. A failed deployment or a stop for restart leaves media in temp for a retry. Repeated validation does not extend the original freshness limit. If routine temp cleanup purges it first, the next run downloads fresh media.
- Once Office and all selected companion apps are verified installed, the same script run deletes its entire temporary workspace, including the Office payload, ODT package/extraction, companion bootstrappers, cache manifest, helper copy, generated XML, and temporary process logs. It also removes unused older temporary deployment workspaces and known installer downloads from older ProgramData stages. Deferred-user files in ProgramData, installed applications, and Microsoft's servicing caches are preserved.
- There is **no daily housekeeping task, resident housekeeping script, or separate log-retention job**. Validation/failure leftovers are subject to the endpoint's existing temp-cleanup routines; exact deletion timing depends on those routines. File removal rejects junctions/symlinks and skips workspaces referenced by running processes.
- Cleanup failures do not change a verified installation into an installation failure. `ArtifactCleanupPending=true` and a console warning identify files left behind; there is no scheduled retry. A later successful deployment or the endpoint's ordinary temp cleanup can remove them.
Earlier ProgramData caches are not searched for reuse in the new temp location. Their known installer files are still cleaned after a successful deployment, while existing user helpers and diagnostic files are preserved. An RMM hard termination can interrupt cleanup; leftovers remain in temp rather than depending on a new background process.
## 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` | Office and companion apps installed, but user cleanup is pending or incomplete. `InstalledWithUserCleanupPending`: sign in as the listed `PendingUserSids` and inspect task results. `InstalledWithUserCleanupIncomplete`: also review `UserCleanupRegistrationFailures`; those users do not have a registered cleanup task. 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.
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, options, and generated XML are temporary files in the reported `Workspace`. They remain after a failed or validation-only run until a later successful deployment or routine temp cleanup removes them; they are deleted after successful installation. ODT removal uses `office-remove.stdout.log` / `.stderr.log` and `remove.xml`; installation uses `office-install.stdout.log` / `.stderr.log` and `install.xml`. The main Tools log retains the actions, results, and receipt and is not deleted. The separate limited-user cleanup task does not share the elevated Tools execution context; its small transcript remains in `%LOCALAPPDATA%\Emberkom\OfficeDeployment\.log` for each user. Do not manually delete `UserCleanupWorkspace` 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. They require Windows PowerShell 5.1 and exercise the default validation gate (including `Force`), explicit deployment opt-out, log/console routing with the real Tools helpers, XML, removal-result handling, bounded cache deletion, companion installer failures/verification, deferred cleanup protection, and the unchanged `Run-Script` receiving injected strings through the shim with a mocked workload. Recovery checks simulate busy MSI, delayed registration, transient downloads, Appx removal races, persistent failures, and completed-task housekeeping errors. ODT removal tests cover silent XML, absent Office, mixed MSI/Click-to-Run installations, leftovers, read errors, MSI verification after installation, restart results, and absence of an interactive fallback. An inert executable checks actual native argument passing; a 32-bit Windows PowerShell child checks relaunch into 64-bit Windows PowerShell 5.1 and exit-code propagation. Tests use a separate mutex and do not run Microsoft installers or clear actual credentials.
`Run-Script` is unchanged. Its existing local execution can read the Syncro variables from the enclosing caller scope. The Office workload validates those values and reports its own result and exit code. The shim only sets TLS, dot-sources `Tools.ps1`, and invokes the workload. Existing `Run-Script` bootstrap failure behavior also remains unchanged.
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.