diff --git a/AGENTS.md b/AGENTS.md index 257429b..5272ce5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,6 +2,11 @@ ## RMM script execution model +This is the required convention for new RMM scripts. Read both +[`Install-MicrosoftOffice365.ps1`](Install-MicrosoftOffice365.ps1) and its +[`rmm/Install-MicrosoftOffice365.ps1`](rmm/Install-MicrosoftOffice365.ps1) caller +as the reference implementation before designing script inputs or a loader. + Scripts in this repository are generally executed by a small caller script in the RMM. The caller first downloads and dot-sources `Tools.ps1` from the public repository URL: ```powershell @@ -14,8 +19,72 @@ The caller then invokes `Run-Script`, passing the repository script's filename w Run-Script -LivePSScript Create-BatteryReport ``` -For a live PowerShell script without `-Arguments`, `Run-Script` downloads the target script and dot-sources it. This keeps the core script logic in version control, and changes pushed to the repository take effect in production without updating each RMM caller. +The live-script calling convention preserves the caller's PowerShell context so +the downloaded core can read the caller's variables. Dot-sourcing (`. $ScriptFile` +or `. $ScriptBlock`) is the standard way to provide this shared scope. Keep the +core logic in version control so repository updates take effect without replacing +each RMM caller. `Run-Script` has separate execution branches; verify variable +visibility against the actual helper when changing a loader. -When a repository script needs RMM-provided input, define the variable in the RMM caller before calling `Run-Script`. Because the target is dot-sourced into the caller's scope, it can read that variable directly. +When a repository script needs RMM-provided input, define the variable in the RMM caller before calling `Run-Script`. The downloaded core reads that variable directly from the inherited scope. When changing `Run-Script` or scripts invoked through it, preserve this shared-scope behavior unless the change explicitly includes migrating all affected RMM callers. + +## RMM inputs are caller variables containing strings + +- Define/configure operator inputs in the RMM shim, before loading the core. The + RMM supplies **strings only**, even for boolean, integer, and list settings. +- The core reads inherited variables, as the Office installer does. Do **not** + introduce script-level `param(...)` blocks, command-line flags, or a public + `-Options` hashtable for RMM settings. Helper functions inside a script may + still declare parameters for their internal interfaces. +- Do not pass RMM settings through `Run-Script -Arguments`. Use + `Run-Script -LivePSScript ` with caller variables + already defined. Do not add a new PowerShell process/runspace for convenience: + it does not inherit those variables. If a new process is required, explicitly + transfer the inputs, as the Office installer does for its native-host relaunch. +- Never overwrite values injected by the RMM. When defaults are appropriate, + distinguish a missing variable from a supplied blank/false value. A core can + use `Get-Variable -Name ... -ErrorAction SilentlyContinue` to collect optional + inputs without redefining them or relying on a script parameter block. +- Convert boolean strings with **`ConvertTo-RmmBoolean` from `Tools.ps1`**. + Never use `[bool]$Text`: a nonempty string such as `'false'` casts to true. +- Parse semicolon-separated list strings with + **`@(ConvertTo-RmmList -Value $Text)` from `Tools.ps1`**. The helper trims items + and removes empty entries; `@(...)` ensures an array for zero/one/many items. + It does not validate or resolve paths. Validate share names/paths in the core + according to the workload. Keep reusable conversion helpers in `Tools.ps1`; + do not duplicate their implementation in individual scripts. +- Parse integer strings explicitly and validate the allowed range. Keep the + original caller values intact and use separate normalized internal values. +- For a permanent endpoint shim launched later by a backup agent, persist its + configured **string** values in that shim. Variables injected into an earlier + RMM process do not survive into the backup agent's new PowerShell process. + +Example values in a caller (the RMM may inject these rather than assigning them +in the script): + +```powershell +$QuickBooksShareNames = 'QBData;QBArchive' +$QuickBooksForceClose = 'true' +$QuickBooksGraceSeconds = '60' +``` + +## Tools loading and verification + +- Download `Tools.ps1` live when needed. **Do not cache `Tools.ps1` or its helper + definitions**, or introduce an offline Tools fallback. This is an explicit + repository preference; the cloud-backup workflow requires network access. +- Set TLS 1.2 before the first HTTPS download on Windows PowerShell 5. +- Normally dot-source live `Tools.ps1` as shown above, then call `Run-Script`. + The QuickBooks permanent backup shim has a documented specialized loader: it + downloads Tools live and dot-sources only its two conversion definitions to + avoid running unrelated setup/logging during backup. This is not a reason to + replace the standard loader in other scripts. Each QuickBooks shim downloads + its matching root script (Stop or Start), which downloads the shared routines + from `resources/quickbooks/QuickBooksBackup.ps1`. All code is fetched live; + only recovery state/logs persist. Start must not call a local Stop shim or use + a cached Stop script in a hidden restore mode. +- Use focused Windows PowerShell 5 tests to verify actual shim-to-core input + visibility, string-to-boolean/list conversion, and exit-code propagation when + changing these boundaries. Mock downloads and disruptive actions during tests. diff --git a/Install-MicrosoftOffice365.ps1 b/Install-MicrosoftOffice365.ps1 index 8e38e2c..87e594a 100644 --- a/Install-MicrosoftOffice365.ps1 +++ b/Install-MicrosoftOffice365.ps1 @@ -32,7 +32,7 @@ function Get-OfficeDeploymentDefinitions { OdtPage = 'https://www.microsoft.com/en-us/download/details.aspx?id=49117' OdtDownloadPattern = 'https://download\.microsoft\.com/[^"\s<>]+/officedeploymenttool_[a-zA-Z0-9_-]+\.exe' ManualScrubUrl = 'https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-office-uninstall' - HelperVersion = 'EmberkomOfficeUserCleanup-v4' + HelperVersion = 'EmberkomOfficeUserCleanup-v5' Language = 'en-us' OfficeBuildPattern = '^16\.0\.\d+\.\d+$' OdtExcludedApps = @('Groove', 'OneDrive', 'Lync', 'Teams', 'OutlookForWindows') @@ -61,6 +61,11 @@ function Get-OfficeDeploymentDefinitions { 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. @@ -192,6 +197,7 @@ function New-OfficeWorkspace { ) # Executable content must never be writable by a standard user. # Default to the execution account's temp location (SYSTEM under Syncro). + Assert-OfficeManagedPath $root (Join-Path $root $DeploymentId) $null = New-Item -ItemType Directory -Path $root -Force -ErrorAction Stop for ($item = Get-Item -LiteralPath $root -Force; $null -ne $item; $item = $item.Parent) { if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Deployment path traverses a reparse point: $($item.FullName)" } @@ -213,15 +219,60 @@ function New-OfficeWorkspace { function New-OfficeUserWorkspace { param($Media, [string]$Workspace) - # Only deferred user cleanup must survive routine temp purges. SYSTEM's temp - # directory may also be inaccessible to the limited users who run this helper. + # Persist only synchronization state for deferred tasks. They fetch code live; + # no downloaded helper or installation payload survives in ProgramData. $path = New-OfficeWorkspace -Root (Join-Path $env:ProgramData 'EmberkomOfficeDeployment') -DeploymentId (Split-Path -Leaf $Workspace) - $helper = Join-Path $path 'Office-UserCleanup.ps1' - Copy-Item -LiteralPath $Media.Helper -Destination $helper -ErrorAction Stop - $Media.Helper = $helper $path } +function Assert-OfficeWritablePath { + param([string]$Path) + $target = [IO.Path]::GetFullPath($Path) + # Probe the closest existing parent without creating the intended directory. + $parent = $target + while (!(Test-Path -LiteralPath $parent)) { + $parent = Split-Path -Parent $parent + if (!$parent) { throw "No existing parent for deployment path: $target" } + } + Assert-OfficeManagedPath $parent (Join-Path $parent 'office-write-probe') + if (!(Test-Path -LiteralPath $parent -PathType Container)) { throw "Deployment parent is not a directory: $parent" } + $probePath = Join-Path $parent ('OfficeWriteProbe-' + [guid]::NewGuid().ToString('N') + '.tmp') + $probe = $null + try { + $probe = [IO.FileStream]::new($probePath, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None, 1, [IO.FileOptions]::DeleteOnClose) + } catch { throw "Deployment path is not writable: $target (tested $parent). $($_.Exception.Message)" } + finally { if ($probe) { $probe.Dispose() } } + $null = Write-Output "Writable path verified: $target (tested existing directory $parent)." + [pscustomobject]@{ Path=$target; TestedDirectory=$parent } +} + +function Test-OfficeDownloadLinks { + param($Options) + $definitions = Get-OfficeDeploymentDefinitions + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + $links = @($definitions.OdtPage, "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1") + if ($Options.OfficeFeatureRelease) { $links += $definitions.OfficeReleaseHistory } + $channel = $definitions.OfficeCdnChannels[$Options.UpdateChannel] + $links += "https://officecdn.microsoft.com/pr/$channel/Office/Data/v$($Options.OfficeArchitecture).cab" + foreach ($name in @('WebView2', 'NewOutlook', 'OneDrive', 'Teams')) { + if ($name -eq 'Teams' -and !$Options.InstallTeams) { continue } + $installer = $definitions.CompanionInstallers[$name] + if ($name -eq 'OneDrive') { + $arch = if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64' -or $env:PROCESSOR_ARCHITEW6432 -eq 'ARM64') { 'ARM64' } elseif ([Environment]::Is64BitOperatingSystem) { 'x64' } else { 'x86' } + $links += $installer.Uris[$arch] + } else { $links += $installer.Uri } + } + foreach ($uri in $links) { + # HEAD follows redirects but never requests a body or writes a download. + # A server that refuses HEAD fails assessment; do not fall back to GET. + try { $response = Invoke-WebRequest -UseBasicParsing -Method Head -Uri $uri -MaximumRedirection 10 -TimeoutSec $definitions.OdtPageTimeoutSeconds -ErrorAction Stop } + catch { throw "HTTP HEAD check failed for $uri. $($_.Exception.Message)" } + if ([int]$response.StatusCode -ne 200) { throw "HTTP HEAD check for $uri returned $($response.StatusCode); expected 200." } + $null = Write-Output "HTTP HEAD 200: $uri" + [pscustomobject]@{ Uri=$uri; StatusCode=200; Method='HEAD' } + } +} + function Assert-OfficeManagedPath { param([string]$Root, [string]$Path) $base = [IO.Path]::GetFullPath($Root).TrimEnd('\') @@ -256,12 +307,6 @@ function Remove-OfficeManagedItem { Remove-Item -LiteralPath ([IO.Path]::GetFullPath($Path)) -Recurse -Force -ErrorAction Stop } -function Get-OfficeStagingNames { - # Only our downloaded artifacts; never Office's installed files or servicing caches. - @('ODT', 'odt.exe', 'odt-download-page.html', 'GetHelp', 'GetHelp.zip', 'media-cache.json') - foreach ($installer in (Get-OfficeDeploymentDefinitions).CompanionInstallers.Values) { $installer.File } -} - function Assert-OfficeDiskSpace { param( [string]$Workspace, @@ -299,13 +344,62 @@ function Remove-OfficeStagingFiles { if (Test-OfficeStagingInUse $Workspace $processes) { throw 'An installer or a process referencing this workspace is still running.' } # Check every artifact before deleting any part of the payload. The caller holds # the deployment mutex; these probes also protect against surviving child processes. - foreach ($name in (Get-OfficeStagingNames)) { - foreach ($file in @(Get-OfficeManagedFiles $Root (Join-Path $Workspace $name))) { - $probe = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None) - $probe.Dispose() + $files = @(Get-OfficeManagedFiles $Root $Workspace | Where-Object { $_.Extension -notin @('.log', '.etl') }) + foreach ($file in $files) { + $probe = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None) + $probe.Dispose() + } + foreach ($file in $files) { Remove-OfficeManagedItem $Root $file.FullName } + # Preserve nested logs and their parents, but discard empty payload folders. + foreach ($folder in @(Get-ChildItem -LiteralPath $Workspace -Directory -Recurse -Force -ErrorAction Stop | Sort-Object { $_.FullName.Length } -Descending)) { + Assert-OfficeManagedPath $Root $folder.FullName + if (!@(Get-ChildItem -LiteralPath $folder.FullName -Force -ErrorAction Stop).Count) { Remove-Item -LiteralPath $folder.FullName -Force -ErrorAction Stop } + } +} + +function Get-OfficeDeploymentRoots { + $parents = @([IO.Path]::GetTempPath(), (Join-Path $env:WINDIR 'Temp'), (Join-Path $env:WINDIR 'SystemTemp'), $env:ProgramData) + foreach ($profile in @(Get-CimInstance Win32_UserProfile -ErrorAction Stop)) { + if ($profile.LocalPath) { $parents += Join-Path $profile.LocalPath 'AppData\Local\Temp' } + } + @($parents | Where-Object { $_ } | ForEach-Object { [IO.Path]::GetFullPath((Join-Path $_ 'EmberkomOfficeDeployment')).TrimEnd('\') } | Sort-Object -Unique) +} + +function Clear-OfficePreviousDeploymentFiles { + # The deployment mutex is held by the caller. Never import options, XML or media + # from these folders; the reserved root and GUID identify our prior workspaces. + $roots = @(Get-OfficeDeploymentRoots) + $processes = @(Get-CimInstance Win32_Process -ErrorAction Stop) + foreach ($root in $roots) { + if (Test-OfficeStagingInUse $root $processes) { throw "A surviving installer is running. Stop the previous deployment before removing old artifacts in $root." } + Assert-OfficeManagedPath $root (Join-Path $root 'path-check') + } + $tasks = @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -match '^Emberkom-OfficeCleanup-[a-f0-9]{32}-S-1-[\d-]+$' }) + if (@($tasks | Where-Object { $_.State -in @('Running', 'Queued') }).Count) { throw 'Previous Office user cleanup is still running. Wait for it to finish before redeploying.' } + foreach ($task in $tasks) { + $null = Disable-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -ErrorAction Stop + if ((Get-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -ErrorAction Stop).State -in @('Running', 'Queued')) { throw "Previous user cleanup started during preparation: $($task.TaskName)." } + Unregister-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -Confirm:$false -ErrorAction Stop + $null = Write-Output "Retired previous user cleanup task; this deployment will schedule fresh cleanup: $($task.TaskName)" + } + foreach ($root in $roots) { + # Older validation runs wrote release metadata beside the staging root. + # New runs keep it inside their GUID workspace, including partial downloads. + $parent = Split-Path -Parent $root + if (Test-Path -LiteralPath $parent -PathType Container) { + foreach ($file in @(Get-ChildItem -LiteralPath $parent -File -Filter 'OfficeReleaseHistory-*.html' -ErrorAction Stop | Where-Object { $_.Name -match '^OfficeReleaseHistory-[a-f0-9]{32}\.html$' })) { + Assert-OfficeManagedPath $parent $file.FullName + $probe = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None) + $probe.Dispose() + Remove-OfficeManagedItem $parent $file.FullName + } + } + if (!(Test-Path -LiteralPath $root)) { continue } + foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -Force -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' })) { + Remove-OfficeStagingFiles $root $folder.FullName + if (!@(Get-ChildItem -LiteralPath $folder.FullName -Force -ErrorAction Stop).Count) { Remove-OfficeManagedItem $root $folder.FullName } } } - foreach ($name in (Get-OfficeStagingNames)) { Remove-OfficeManagedItem $Root (Join-Path $Workspace $name) } } function Test-OfficeStagingInUse { @@ -313,6 +407,7 @@ function Test-OfficeStagingInUse { # Be conservative even when a child installer no longer names its source folder. foreach ($process in $Processes) { if ($process.Name -in @('setup.exe', 'odt.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe')) { return $true } + if ($process.Name -eq 'OfficeClickToRun.exe' -and $process.CommandLine -notmatch '(?i)\s/(service|user)\s*$') { return $true } foreach ($value in @($process.CommandLine, $process.ExecutablePath)) { if ($value -and $value.IndexOf($Workspace, [StringComparison]::OrdinalIgnoreCase) -ge 0) { return $true } } @@ -323,17 +418,16 @@ function Test-OfficeStagingInUse { function Complete-OfficeDeploymentFiles { param([string]$Workspace, [string]$UserWorkspace) $warnings = @() - # Called from finally on success, failure and restart exits. Keep small logs/XML - # for diagnosis; remove only our disposable media after native processes release it. + # Called from finally on success, failure and restart exits. Only logs remain + # in the download workspace after native processes release it. try { $root = Split-Path -Parent $Workspace Remove-OfficeStagingFiles $root $Workspace - Remove-OfficeManagedItem $root (Join-Path $Workspace 'Office-UserCleanup.ps1') } catch { $warnings += "$Workspace : $($_.Exception.Message)" Write-Error "Deployment media cleanup deferred: $($warnings[-1])" -ErrorAction Continue } - # Only pass UserWorkspace after a completed installation. Pending helpers survive. + # Pending tasks need only their lock and phase marker, not downloaded code. if ($UserWorkspace -and $UserWorkspace -ne $Workspace) { try { $id = Split-Path -Leaf $UserWorkspace @@ -351,12 +445,13 @@ function Complete-OfficeDeploymentFiles { } function Resolve-OfficeTargetVersion { - param($Options) + param($Options, [Parameter(Mandatory=$true)][string]$Workspace) $Options.TargetOfficeVersion = '' if (!$Options.OfficeFeatureRelease) { return } $definitions = Get-OfficeDeploymentDefinitions - # Small metadata only, including in validation. No persistent staging directory. - $historyPath = Join-Path ([IO.Path]::GetTempPath()) ('OfficeReleaseHistory-' + [guid]::NewGuid().ToString('N') + '.html') + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + # Deployment only. Assessment checks HEAD without resolving/downloading metadata. + $historyPath = Join-Path $Workspace 'office-release-history.html' try { Save-OfficeDownload $definitions.OfficeReleaseHistory $historyPath $Options.TargetOfficeVersion = Get-OfficeBuildFromHistory (Get-Content -LiteralPath $historyPath -Raw -ErrorAction Stop) $Options.UpdateChannel $Options.OfficeFeatureRelease @@ -530,7 +625,7 @@ function Initialize-OfficeMedia { param($Options, [string]$Workspace) $definitions = Get-OfficeDeploymentDefinitions [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 - if ($Options.OfficeFeatureRelease -and !$Options.TargetOfficeVersion) { Resolve-OfficeTargetVersion $Options } + if ($Options.OfficeFeatureRelease -and !$Options.TargetOfficeVersion) { Resolve-OfficeTargetVersion $Options $Workspace } Assert-OfficeDiskSpace -Workspace $Workspace -DownloadingMedia # Download only in the install workflow; no persistent cache or cross-run reuse. $helper = Join-Path $Workspace 'Office-UserCleanup.ps1' @@ -553,6 +648,8 @@ function Initialize-OfficeMedia { $removal = New-OfficeRemovalConfiguration $Options; $removal.Save($removalPath) $configPath = Join-Path $Workspace 'install.xml' $config = New-OfficeConfiguration $Options $odtFolder $Options.TargetOfficeVersion; $config.Save($configPath) + $null = Write-Output "Office removal configuration: $($removal.OuterXml)" + $null = Write-Output "Office installation configuration: $($config.OuterXml)" $null = Write-Output 'Downloading Office installation files before removing installed apps.' for ($attempt = 1; $attempt -le $definitions.DownloadAttempts; $attempt++) { $prefix = if ($attempt -eq 1) { 'office-download' } else { "office-download.retry-$attempt" } @@ -711,6 +808,41 @@ function Get-OfficeSuiteInventory { } } +function Get-OfficeClickToRunState { + # Finished-product inventory misses interrupted installations. Read servicing + # state as evidence only; ODT, not registry deletion, must remove the old setup. + $root = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun' + $present = Test-Path -LiteralPath $root -ErrorAction Stop + $sources = @(); $working = @() + if ($present) { + $keys = @((Get-Item -LiteralPath $root -ErrorAction Stop)) + @(Get-ChildItem -LiteralPath $root -Recurse -ErrorAction Stop) + foreach ($key in $keys) { + $values = Get-ItemProperty -LiteralPath $key.PSPath -ErrorAction Stop + foreach ($property in $values.PSObject.Properties) { + if ($property.Name -like 'PS*') { continue } + foreach ($value in @($property.Value)) { + if ($value -isnot [string] -or !$value.Trim()) { continue } + if ($value -match '(?i)EmberkomOfficeDeployment[\\/]') { $sources += "$($key.Name) : $($property.Name) = $value" } + if ($property.Name -match '^WorkingConfig(uration)?$' -and $value.Trim('{}') -ne '00000000-0000-0000-0000-000000000000') { $working += $value } + } + } + } + } + $service = Get-Service -Name ClickToRunSvc -ErrorAction SilentlyContinue + [pscustomobject]@{ Present=($present -or $null -ne $service); SourceReferences=$sources; WorkingConfiguration=$working } +} + +function Assert-OfficeFreshInstallState { + $cleared = Wait-OfficeResult { + $state = Get-OfficeClickToRunState + !$state.SourceReferences.Count -and !$state.WorkingConfiguration.Count + } 'removal of previous Click-to-Run working configuration and deployment source references' + if (!$cleared) { + $state = Get-OfficeClickToRunState + throw "Click-to-Run still retains previous deployment state after ODT removal. Installation stopped to prevent reuse of old content. Working configuration: $($state.WorkingConfiguration -join ', '). Source references: $($state.SourceReferences -join '; '). Arrange an attended Office repair/scrub: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)" + } +} + function Remove-OfficeSuite { param($Media, [string]$Workspace) # Get Help can create an interactive elevated child despite a hidden SYSTEM parent. @@ -718,12 +850,13 @@ function Remove-OfficeSuite { $existing = @(Get-OfficeSuiteInventory) $msi = @($existing | Where-Object { $_.WindowsInstaller -eq 1 }) if ($msi.Count) { $null = Write-Output "MSI Office will be removed by ODT RemoveMSI before it installs the replacement suite: $($msi.DisplayName -join '; ')." } - if (!@($existing | Where-Object { $_.WindowsInstaller -ne 1 }).Count) { - $null = Write-Output 'No non-MSI Office products detected; skipping the separate ODT removal pass.' + $state = Get-OfficeClickToRunState + if (!@($existing | Where-Object { $_.WindowsInstaller -ne 1 }).Count -and !$state.Present) { + $null = Write-Output 'No Click-to-Run products, service or servicing state detected; skipping the separate ODT removal pass.' return 0 } if (!$Media.RemovalConfig -or !(Test-Path -LiteralPath $Media.RemovalConfig -PathType Leaf)) { throw 'The staged silent Office removal configuration is missing.' } - $null = Write-Output 'Silently removing Click-to-Run Office, including Visio and Project, with ODT.' + $null = Write-Output 'Silently removing Click-to-Run Office, including incomplete deployments, Visio and Project, with ODT.' $code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.RemovalConfig)`"" (Join-Path $Workspace 'office-remove') $manual = "No interactive scrubber was launched. Arrange an attended manual scrub if needed: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl)" if ($code -notin @(0, 3010)) { throw "Silent ODT Office removal failed (exit $code). See logs in $Workspace. $manual" } @@ -927,6 +1060,25 @@ function Clear-OfficeProfileIdentity { } } +function New-OfficeUserCleanupCommand { + param([ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId) + $definitions = Get-OfficeDeploymentDefinitions + $uri = "$($definitions.RepositoryRoot)/resources/office/Office-UserCleanup.ps1".Replace("'", "''") + $version = $definitions.HelperVersion.Replace("'", "''") + $command = @' +$ErrorActionPreference = 'Stop' +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +try { + $client = New-Object Net.WebClient + try { $source = $client.DownloadString('__URI__') } finally { $client.Dispose() } + if (!$source.Contains('__VERSION__')) { throw 'Office user cleanup helper version does not match its deployment.' } + & ([scriptblock]::Create($source)) -DeploymentId '__ID__' +} catch { Write-Error $_ -ErrorAction Continue; exit 1 } +'@ + $command = $command.Replace('__URI__', $uri).Replace('__VERSION__', $version).Replace('__ID__', $DeploymentId) + [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command)) +} + function Start-OfficeUserCleanup { param([object[]]$Profiles, $Media, [string]$Workspace) $definitions = Get-OfficeDeploymentDefinitions @@ -934,7 +1086,8 @@ function Start-OfficeUserCleanup { foreach ($profile in $Profiles) { $name = "Emberkom-OfficeCleanup-$deploymentId-$($profile.SID)" try { - $action = New-ScheduledTaskAction -Execute "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$($Media.Helper)`" -DeploymentId $deploymentId" -ErrorAction Stop + $command = New-OfficeUserCleanupCommand $deploymentId + $action = New-ScheduledTaskAction -Execute "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand $command" -ErrorAction Stop $principal = New-ScheduledTaskPrincipal -UserId $profile.SID -LogonType Interactive -RunLevel Limited -ErrorAction Stop $trigger = New-ScheduledTaskTrigger -AtLogOn -User $profile.SID -ErrorAction Stop $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes $definitions.UserCleanupTaskMinutes) -MultipleInstances IgnoreNew -ErrorAction Stop @@ -988,7 +1141,7 @@ function Install-OfficeMedia { if (!(Test-Path -LiteralPath $key -ErrorAction Stop)) { return $false } $installed = Get-ItemProperty -LiteralPath $key -ErrorAction Stop if ($Options.ProductId -notin ($installed.ProductReleaseIds -split ',') -or $installed.Platform -ne $platform -or $installed.VersionToReport -notmatch (Get-OfficeDeploymentDefinitions).OfficeBuildPattern) { return $false } - # Unpinned ODT can install a newer build than the earlier validation download. + # Unpinned ODT can install a newer build than this run's earlier download. # Windows 10 must still match its explicitly selected compatible build. if ($Options.TargetOfficeVersion) { if ($installed.VersionToReport -ne $Options.TargetOfficeVersion) { return $false } @@ -1025,23 +1178,31 @@ function Invoke-OfficeDeployment { foreach ($profile in $profiles) { if (!(Test-Path -LiteralPath (Join-Path $profile.LocalPath 'NTUSER.DAT'))) { throw "Profile $($profile.SID) is unavailable. Mount its profile/container before deploying." } } - Resolve-OfficeTargetVersion $Options $stagingRoot = Join-Path ([IO.Path]::GetTempPath()) 'EmberkomOfficeDeployment' - Assert-OfficeDiskSpace -Workspace $stagingRoot -DownloadingMedia + $paths = @($stagingRoot, (Join-Path $env:ProgramData 'EmberkomOfficeDeployment'), $env:ProgramFiles, ${env:ProgramFiles(x86)}) + $writablePaths = @($paths | Where-Object { $_ } | Select-Object -Unique | ForEach-Object { Assert-OfficeWritablePath $_ }) if ($Options.ValidateBeforeChanges) { + Assert-OfficeDiskSpace -Workspace $stagingRoot -DownloadingMedia + $downloadChecks = @(Test-OfficeDownloadLinks $Options) $existingOffice = @(Get-OfficeSuiteInventory | ForEach-Object { $_.DisplayName }) - $null = Write-Output 'Validation passed. No installation media downloaded or staging workspace created. Installation will repeat prerequisites and verify downloads before removal.' + $state = Get-OfficeClickToRunState + $null = Write-Output 'Assessment passed. HTTP HEAD checks returned 200; no response bodies downloaded or deployment directory created. Exact ODT package and Office build resolution/signature verification occur only during deployment.' return [pscustomobject]@{ OfficeDeploymentStatus='ValidationPassed'; ExitCode=0; ValidateBeforeChanges=$true ProductId=$Options.ProductId; OfficeVersion=$Options.TargetOfficeVersion; Architecture=$Options.OfficeArchitecture UpdateChannel=$Options.UpdateChannel; Company=$Options.Company; TeamsSelected=$Options.InstallTeams; OfficeRemovalMethod='SilentODT'; DeferReboot=$Options.DeferReboot Workspace=$null; ExistingOffice=$existingOffice; ProfileCount=$profiles.Count; RunningApps=$runningApps; MediaDownloaded=$false + WritablePaths=$writablePaths; DownloadChecks=$downloadChecks; ClickToRunState=$state; OfficeFeatureRelease=$Options.OfficeFeatureRelease; MetadataResolved=$false NextStep='Set ValidateBeforeChanges=false to download, verify, deploy, and clean up installation media. Prerequisites are checked again.' } } + Clear-OfficePreviousDeploymentFiles + Assert-OfficeDiskSpace -Workspace $stagingRoot -DownloadingMedia $workspace = New-OfficeWorkspace $null = Write-Output "Temporary deployment workspace: $workspace" - $Options | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $workspace 'options.json') -Encoding UTF8 + # Keep the request in a diagnostic log; XML and options are never reused. + $Options | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $workspace 'deployment-options.log') -Encoding UTF8 + Resolve-OfficeTargetVersion $Options $workspace $media = Initialize-OfficeMedia $Options $workspace Assert-OfficeDiskSpace -Workspace $workspace Stop-OfficeDeploymentApps $Options @@ -1057,6 +1218,7 @@ function Invoke-OfficeDeployment { $receipt = [pscustomobject]@{ OfficeDeploymentStatus = 'RestartRequiredBeforeInstall'; ExitCode = 3010; RestartRequired = $true; DeferReboot = $Options.DeferReboot; RestartStage = 'OfficeRemoval'; Workspace = $workspace; PendingUserSids = @(); ArtifactCleanupPending=$false } return $receipt } + Assert-OfficeFreshInstallState foreach ($profile in $profiles) { Clear-OfficeProfileIdentity $profile } $userWorkspace = $workspace if ($profiles.Count) { $userWorkspace = New-OfficeUserWorkspace $media $workspace } @@ -1079,8 +1241,11 @@ function Invoke-OfficeDeployment { if ($workspace) { try { $cleanupWarnings = Complete-OfficeDeploymentFiles $workspace $(if ($completed) { $userWorkspace } else { $null }) } catch { $cleanupWarnings = @($_.Exception.Message); Write-Error "Office media cleanup failed: $($cleanupWarnings[0])" -ErrorAction Continue } - if ($receipt) { $receipt.ArtifactCleanupPending = $cleanupWarnings.Count -gt 0 } - if ($cleanupWarnings.Count) { $null = Write-Output 'Some deployment media remains; review the log and use OfficeStaging cleanup after installer processes finish.' } + if ($receipt) { + $receipt.ArtifactCleanupPending = $cleanupWarnings.Count -gt 0 + if ($cleanupWarnings.Count -and $receipt.ExitCode -eq 0) { $receipt.ExitCode = 2; $receipt.OfficeDeploymentStatus = 'InstalledWithArtifactCleanupPending' } + } + if ($cleanupWarnings.Count) { $null = Write-Output 'Some deployment artifacts could not be removed safely. Stop surviving installers before rerunning; the next deployment must clean prior artifacts before downloading fresh media.' } } if ($locked) { $mutex.ReleaseMutex() } $mutex.Dispose() @@ -1134,9 +1299,9 @@ function Invoke-OfficeDeploymentEntry { } $null = Write-Output "Office deployment host: Windows PowerShell $($PSVersionTable.PSVersion), $([IntPtr]::Size * 8)-bit." if ($options.ValidateBeforeChanges) { - Microsoft.PowerShell.Utility\Write-Output 'Validation only: checking prerequisites and optional release metadata. No installation media downloads, staging, app shutdown, Office/user cleanup, or installation will run.' + Microsoft.PowerShell.Utility\Write-Output 'Validation only: checking prerequisites, writable paths and HTTP HEAD 200 responses. No metadata or payload downloads, deployment directory, artifact cleanup, app shutdown, or installation will run.' } else { - Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: validating and staging media, then silently removing Office with ODT and reinstalling Office and the selected companion apps.' + Microsoft.PowerShell.Utility\Write-Output 'Deployment enabled: clearing prior artifacts, downloading fresh media, then silently removing Office with ODT and installing the selected apps. Download workspaces retain only logs after cleanup.' } Microsoft.PowerShell.Utility\Write-Output "Diagnostic log: $Global:LogFile" $results = @(Invoke-OfficeDeployment -Options $options) diff --git a/README.md b/README.md index 855966a..e8218e9 100644 --- a/README.md +++ b/README.md @@ -14,12 +14,33 @@ You can then run any of the scripts using the Run-Script function: If you're using an RMM tool, the scripts in the /rmm directory are all that's needed to hook the main script in this directory. +For QuickBooks image-backup preparation, use [Stop-QuickBooksDesktop.ps1](Stop-QuickBooksDesktop.ps1) +and [Start-QuickBooksDesktop.ps1](Start-QuickBooksDesktop.ps1). The permanent +[stop shim](rmm/Stop-QuickBooksDesktop.ps1) defines the host's exact company-file +share names as a semicolon-separated string and pairs with the +[start shim](rmm/Start-QuickBooksDesktop.ps1). See [deployment, exit codes, and +recovery](docs/QuickBooks-Backup.md) before scheduling: desktop, database-service, +share-isolation, or open-handle failures prevent backup; post restores the +recorded services and share access. Each shim downloads its matching repository +script, `Tools.ps1`, and the shared QuickBooks routines live on every run. Only +the two shims need deployment; recovery state persists locally and no code is cached. + For DSA collection, paste [rmm/Get-DSAManifest.ps1](rmm/Get-DSAManifest.ps1) into the RMM caller, preserving its configured platform variables. This caller selects TLS 1.2 before downloading, stops on bootstrap failure, and dot-sources the downloaded tools in the caller's scope. Updating the repository alone will not change an existing RMM caller. For download failures, use the standalone [Test-FileDownload.ps1](Test-FileDownload.ps1) diagnostic. See [the RMM caller, report guide, and shared caller audit](docs/FileDownload-Diagnostics.md). It compares the existing helper, BITS, and direct GET without changing production download behavior or running downloaded files. `Get-DSAManifest.ps1` uses `Download-FileDirectly`, which passes the original URL to BITS without preliminary `Get-AbsoluteURI` or `IsURLValid` requests. It accepts the same URL and optional `-File` arguments as `Download-File`, waits for completion, and throws on BITS errors. If `-File` is omitted, its temporary filename comes from the original URL; supply `-File` for extensionless URLs or URLs with query strings. Existing `Download-File` callers retain their previous behavior. Publish `Tools.ps1` together with `Get-DSAManifest.ps1` so the new helper is available. +## Environment inventory + +Use [Get-EnvironmentInventory.ps1](Get-EnvironmentInventory.ps1) to collect file +shares, networks, printer connections, wireless observations, and internet egress +into versioned JSON on Windows PowerShell 5.1. Reports describe the environment; +endpoint identity is optional and no Hudu credentials or module are required. +The [RMM caller](rmm/Get-EnvironmentInventory.ps1) supports optional upload through +the existing Filedrop helper. See the [options and data contract](docs/Environment-Inventory.md) +and [JSON schema](resources/environment-inventory/schema-v1.json). No importer is included. + ## Microsoft 365 deployment See [Office365-Deployment.md](docs/Office365-Deployment.md) for the Syncro dropdowns and clean deployment workflow. Upload the shim in `rmm/Install-MicrosoftOffice365.ps1`; publish the core installer and `resources/office/Office-UserCleanup.ps1` together first. The shim uses the existing `Tools.ps1` unchanged; deployment, host relaunch, and result handling live in the main repository script. `ValidateBeforeChanges` defaults to `true` (checks and stages media only); explicitly select `false` to enable deployment. The workload runs in Windows PowerShell 5.1, requires an explicit subscription selection, removes Office and its companion apps, preserves Windows work-account sign-in, and installs the matching suite silently using Microsoft's current ODT. It then installs new Outlook and per-machine OneDrive using Microsoft's signed installers, plus current Teams only when the selected subscription includes Teams. Pending per-user cleanup is reported separately and protects the reinstalled apps. Action/error diagnostics use the existing Tools log; the result is printed to Syncro. @@ -47,6 +68,22 @@ Each input returns a `System.Boolean`: `true`, `$true`, `yes`, `y`, and `1` beco `Get-DSAManifest.ps1` uses this helper for its three options. Publish it together with the updated `Tools.ps1` so the helper is available to the RMM caller. +## Converting RMM lists + +Use `ConvertTo-RmmList` for an RMM string containing semicolon-separated values: + +```powershell +$Paths = @(ConvertTo-RmmList -Value 'C:\QB Data; \\server\Archive;') +$Shares = @(ConvertTo-RmmList -Value $QuickBooksShareNames) +``` + +The helper trims surrounding whitespace and omits empty entries. It preserves +item order, duplicates, case, internal spaces, commas, and backslashes. It does +not evaluate text, resolve paths, or check whether files/shares exist. Semicolons +are always separators; there is no quoting or escaping syntax. Use `@(...)` so +zero, one, and multiple items always produce an array. Publish the updated +`Tools.ps1` with callers that use this new helper. + ## Uploading files After dot-sourcing `Tools.ps1`, scripts can upload a completed file to the Emberkom FileDrop: @@ -72,5 +109,6 @@ powershell.exe -NoProfile -File .\tests\Upload-File.Tests.ps1 powershell.exe -NoProfile -File .\tests\Get-DSAManifest.Tests.ps1 powershell.exe -NoProfile -File .\tests\Download-File.Tests.ps1 powershell.exe -NoProfile -File .\tests\ConvertTo-RmmBoolean.Tests.ps1 +powershell.exe -NoProfile -File .\tests\ConvertTo-RmmList.Tests.ps1 powershell.exe -NoProfile -File .\tests\Get-AllNetworkDrives.Tests.ps1 ``` diff --git a/docs/Office365-Deployment.md b/docs/Office365-Deployment.md index a6a6b85..5de4753 100644 --- a/docs/Office365-Deployment.md +++ b/docs/Office365-Deployment.md @@ -6,7 +6,7 @@ The selection identifies the client's purchased subscription; it does not discov ## 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. +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. @@ -23,7 +23,7 @@ The selection identifies the client's purchased subscription; it does not discov 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. +`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 `` 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. @@ -60,13 +60,13 @@ Business Basic, E1, frontline/web-only plans, education/government variants, con ## Download, removal, and installation -With `ValidateBeforeChanges=true`, the script checks the subscription/activation combination, host and OS prerequisites, running apps, registered profile availability, target release availability when required, and free space. It returns `ValidationPassed` with the deployment plan, existing Office inventory and running apps. It does not create an Office staging workspace, download/extract ODT or any installation media, close apps, uninstall, clear identity/credentials, register tasks, or install apps. `OfficeAppShutdown=Force` only reports running apps; `Abort` fails if any are running. +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. -Windows 10 preflight retrieves small release-history metadata into a temporary file and removes it on success or failure. Other hosts leave the target version unspecified until ODT selects it during installation. Validation still writes the normal Tools log. `Workspace` is null and `MediaDownloaded=false`; `OfficeVersion` is the resolved target on Windows 10 and empty otherwise. Validation does not prove installer download availability, tenant entitlements, future removal/activation, or availability of online companion payloads. +Assessment sends HTTP HEAD requests, follows redirects, and requires status 200 for the ODT discovery page, helper, 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 same prerequisites run again before a fresh workspace is created. The script downloads and verifies the full Office payload and selected bootstrappers, rechecks free space and running apps, performs removal/installation, verifies results, and cleans up media in `finally`. Download failures therefore occur before installed apps are removed. +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. Use `Start-SystemCleanup.ps1` to report/remove abandoned media before retrying; validation never performs housekeeping. +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. @@ -74,7 +74,7 @@ The script resolves the current versioned ODT download from the [Microsoft Downl 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). During prerequisite checks, 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. +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. @@ -97,7 +97,9 @@ A window that offers **Get Microsoft Teams (work or school)** does not by itself 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). +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 also runs this pass when a Click-to-Run service or registry state remains without a finished product registration, as happens after an interrupted installation. Only a host with no non-MSI Office registration and no Click-to-Run service/state skips it. See the [ODT configuration reference](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/office-deployment-tool-configuration-options). + +Before installation, a separate read-only registry check waits for previous Click-to-Run working-configuration markers and references to Emberkom staging paths to disappear. Remaining state or unreadable state stops installation and reports an attended repair/scrub step. Deleting staging files or rebooting alone does not prove that Click-to-Run forgot an unfinished deployment. The script does not delete Microsoft's servicing registry or cache to force this check to pass; the guard is evidence of known stale state, not a guarantee about every internal Office cache. 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. @@ -128,21 +130,21 @@ A file lock serializes user uninstallers with the transition to reinstallation. 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. +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 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. -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. +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\` 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\` directory in the execution account's `[IO.Path]::GetTempPath()`. Under SYSTEM this can be `C:\Windows\SystemTemp`. There is no persistent media cache, manifest creation, or reuse across runs. -- `finally` attempts to delete only downloaded Office/ODT payloads, companion bootstrappers and the temporary helper copy on successful installation, failed download/install, and early restart exits. Installation diagnostics, options, XML and locks remain for troubleshooting. -- Before deleting any media, cleanup rejects links, inventories processes, and probes all candidate files for exclusive access. Active installers or processes referencing the workspace defer cleanup. Process-inventory failures also retain the files. -- Successful install receipts include `MediaDownloaded=true`. `ArtifactCleanupPending=true` flags deferred/failed media cleanup on returned install/restart receipts. Cleanup errors are logged without replacing the original installation error or exit code. -- Deferred per-user helpers remain in their separate ProgramData workspace while tasks still need them. Only a completed installation with no remaining helper tasks or processes can remove that helper workspace. -- Hard RMM termination or power loss can bypass `finally`. The `OfficeStaging` category in `Start-SystemCleanup.ps1` reports/removes recognized abandoned media after `CleanupTempDays` (default seven days), including previous versions' cached downloads. It checks execution/profile temp, Windows Temp/SystemTemp and legacy ProgramData roots while holding the same deployment mutex. Run it first to reclaim old staging space before an installation that fails the free-space check. -- No scheduled housekeeping job is created. Generic temp cleanup excludes the reserved `EmberkomOfficeDeployment` subtree; the dedicated category preserves logs, configuration, helper/task state and unknown files. +- Each actual installation uses a fresh protected `EmberkomOfficeDeployment\` 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 @@ -150,7 +152,7 @@ The helper, lock, and reinstall marker for these previously agreed logon tasks l | --- | --- | | `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. | +| `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. @@ -163,7 +165,7 @@ If machine companion removal still fails verification, the error identifies the 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 installation attempts for troubleshooting; validation creates no staging workspace. Neither payload cleanup nor the dedicated OfficeStaging category deletes these small diagnostic files. 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. +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\.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. @@ -171,7 +173,7 @@ The installer verifies the selected Office product, bitness, and downloaded vers ## 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 artifact deletion on success/failure/restart, metadata removal, active-process and locked-file protection, 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 `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. Existing checks cover strings through the real shim/Tools loader, exit-code propagation, native-host relaunch, deployment order, removal/restart outcomes, 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. diff --git a/resources/office/Office-UserCleanup.ps1 b/resources/office/Office-UserCleanup.ps1 index d9bfcae..95246c5 100644 --- a/resources/office/Office-UserCleanup.ps1 +++ b/resources/office/Office-UserCleanup.ps1 @@ -1,6 +1,6 @@ #Requires -Version 5.1 -# EmberkomOfficeUserCleanup-v4 -# Run only as the affected user, at limited privilege; staged by the Office installer. +# EmberkomOfficeUserCleanup-v5 +# Run only as the affected user, at limited privilege; fetched live by its logon task. param([Parameter(Mandatory = $true)][ValidatePattern('^[a-f0-9]{32}$')][string]$DeploymentId) function Get-OfficeUserCleanupDefinitions { @@ -184,7 +184,9 @@ $null = Start-Transcript -Path (Join-Path $logFolder "$DeploymentId.log") -Appen try { $null = New-Item -Path $marker -Force Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Running' - Invoke-OfficeUserCleanup -Workspace $PSScriptRoot + # The scheduled action fetches this helper live into memory. Only protected + # synchronization state persists on disk; PSScriptRoot is empty in this mode. + Invoke-OfficeUserCleanup -Workspace (Join-Path $env:ProgramData "EmberkomOfficeDeployment\$DeploymentId") Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Complete' } catch { Set-ItemProperty -LiteralPath $marker -Name Status -Value 'Failed' diff --git a/rmm/Install-MicrosoftOffice365.ps1 b/rmm/Install-MicrosoftOffice365.ps1 index a2d4049..cd08707 100644 --- a/rmm/Install-MicrosoftOffice365.ps1 +++ b/rmm/Install-MicrosoftOffice365.ps1 @@ -4,9 +4,9 @@ # See docs/Office365-Deployment.md. # Configure these [string] Dropdown variables in Syncro: # [string]$ValidateBeforeChanges - true (default: validate only), false (remove/reinstall) -# Validation checks prerequisites and small release metadata; it downloads no installation media. -# Install mode downloads before uninstalling and cleans media on success/failure/restart exits. -# Logs and pending per-user cleanup helpers are retained; active installers defer media cleanup. +# Assessment checks writable paths and HTTP HEAD 200; it creates no deployment directory or downloads. +# Deployment clears prior run artifacts, downloads fresh media before uninstalling, and leaves only logs. +# Pending user tasks keep synchronization markers and fetch their helper live. Active installers block cleanup. # [string]$OfficeSubscription - Required; use the exact subscription names in the guide. # [string]$OfficeArchitecture - Auto (default), 64, 32 # [string]$UpdateChannel - Current (default), MonthlyEnterprise, SemiAnnual diff --git a/tests/Install-MicrosoftOffice365.Tests.ps1 b/tests/Install-MicrosoftOffice365.Tests.ps1 index 3f586bb..8cabb31 100644 --- a/tests/Install-MicrosoftOffice365.Tests.ps1 +++ b/tests/Install-MicrosoftOffice365.Tests.ps1 @@ -545,7 +545,7 @@ try { & { function Get-OfficeSuiteInventory { $script:removalChecks++ - if ($script:removalMode -eq 'empty') { return } + if ($script:removalMode -in @('empty','orphan')) { return } [pscustomobject]@{DisplayName='Microsoft Office Professional Plus 2016'; WindowsInstaller=1} if ($script:removalMode -eq 'msi-only') { return } if ($script:removalStarted -and $script:removalMode -eq 'read-error') { throw 'Office inventory is unreadable' } @@ -553,6 +553,7 @@ try { [pscustomobject]@{DisplayName='Microsoft Office Home and Business 2021 - en-us'} } } + function Get-OfficeClickToRunState { [pscustomobject]@{Present=($script:removalMode -eq 'orphan')} } function Invoke-OfficeProcess { param($FilePath,$Arguments,$LogPrefix) $script:removalCalls++; $script:removalStarted=$true @@ -563,7 +564,7 @@ try { $removalPath = Join-Path $testRoot 'remove [literal].xml' (New-OfficeRemovalConfiguration ([pscustomobject]@{OfficeAppShutdown='Force'})).Save($removalPath) $media = [pscustomobject]@{Setup='inert-setup.exe'; RemovalConfig=$removalPath} - foreach ($script:removalMode in @('empty','msi-only','mixed','delayed','remaining','read-error','fatal','reboot')) { + foreach ($script:removalMode in @('empty','orphan','msi-only','mixed','delayed','remaining','read-error','fatal','reboot')) { $script:removalChecks=0; $script:removalCalls=0; $script:removalStarted=$false $script:removalCode = switch ($script:removalMode) { 'fatal' {1603}; 'reboot' {3010}; default {0} } if ($script:removalMode -eq 'remaining') { @@ -581,7 +582,7 @@ try { if ($script:removalMode -eq 'reboot') { Assert-OfficeTest ($script:removalChecks -eq 1) 'A required restart must be surfaced before demanding registration cleanup.' } } $expectedCalls = if ($script:removalMode -in @('empty','msi-only')) {0} else {1} - Assert-OfficeTest ($script:removalCalls -eq $expectedCalls) 'Do not remove absent Click-to-Run Office, rerun failed removal, or launch a fallback scrubber.' + Assert-OfficeTest ($script:removalCalls -eq $expectedCalls) 'Remove orphaned Click-to-Run state even without registered products, without rerunning failed removal or launching a fallback scrubber.' } } & { @@ -833,7 +834,7 @@ try { Assert-OfficeTest ((Get-Content -LiteralPath $Global:LogFile -Raw) -match 'Error: User cleanup task registration failed for unmapped \(C:\\Users\\defaultuser100000\)') 'Registration failures must reach the Tools diagnostic log.' } - # Validation can resolve small release metadata without keeping it or staging media. + # Deployment resolves release metadata and deletes it on success or failure. & { $script:historyPaths=@() function Save-OfficeDownload { @@ -843,17 +844,103 @@ try { [IO.File]::WriteAllText($Path,$script:historyFixture) } $options=Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'} - Resolve-OfficeTargetVersion $options + Resolve-OfficeTargetVersion $options $testRoot Assert-OfficeTest ($script:historyPaths.Count -eq 0 -and !$options.TargetOfficeVersion) 'Unpinned preflight must not download release metadata.' $options.OfficeFeatureRelease='2608'; $script:historyFixture=$releaseHistory - Resolve-OfficeTargetVersion $options + Resolve-OfficeTargetVersion $options $testRoot Assert-OfficeTest ($options.TargetOfficeVersion -eq '16.0.20326.20158' -and !(Test-Path -LiteralPath $script:historyPaths[-1])) 'Resolved metadata must be removed after successful preflight.' $script:historyFixture='No build' - Assert-OfficeThrows { Resolve-OfficeTargetVersion $options } 'did not identify' + Assert-OfficeThrows { Resolve-OfficeTargetVersion $options $testRoot } 'did not identify' Assert-OfficeTest (!(Test-Path -LiteralPath $script:historyPaths[-1])) 'Failed preflight retained release metadata.' } - # Cleanup runs synchronously on every install exit. Downloads are temporary; pending-user - # helpers have a separate durable folder and are never part of disposable media. + # Assessment uses HEAD only, follows redirects, requires 200, and never saves data. + & { + $script:heads=@(); $script:headCode=200; $script:headFails=$false + function Invoke-WebRequest { + param([switch]$UseBasicParsing,$Method,$Uri,$MaximumRedirection,$TimeoutSec,$ErrorAction,[switch]$OutFile) + Assert-OfficeTest ($Method -eq 'Head' -and $MaximumRedirection -eq 10 -and !$OutFile) 'Assessment must use HEAD with redirect handling and no output file.' + $script:heads += $Uri + if ($script:headFails) { throw 'HEAD unsupported' } + [pscustomobject]@{StatusCode=$script:headCode} + } + function Save-OfficeDownload { throw 'Assessment must not download data.' } + $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'} + $checks = @(Test-OfficeDownloadLinks $options) + Assert-OfficeTest ($checks.Count -eq 6 -and $checks.Count -eq $script:heads.Count) 'HEAD checks must cover ODT discovery, helper, CDN, and selected companions.' + Assert-OfficeTest ((Get-OfficeDeploymentDefinitions).CompanionInstallers.Teams.Uri -notin $script:heads) 'No-Teams assessment must not probe the Teams download.' + $options.InstallTeams=$true; $options.OfficeFeatureRelease='2608'; $script:heads=@() + $checks = @(Test-OfficeDownloadLinks $options) + Assert-OfficeTest ($checks.Count -eq 8 -and (Get-OfficeDeploymentDefinitions).OfficeReleaseHistory -in $script:heads) 'Windows 10 assessment must check history availability without resolving the build.' + $script:headCode=204 + Assert-OfficeThrows { Test-OfficeDownloadLinks $options } 'returned 204; expected 200' + $script:headFails=$true + Assert-OfficeThrows { Test-OfficeDownloadLinks $options } 'HEAD check failed.*HEAD unsupported' + $path = Join-Path $testRoot 'not-created\EmberkomOfficeDeployment' + $before = @(Get-ChildItem -LiteralPath $testRoot -Force).Count + $result = Assert-OfficeWritablePath $path + Assert-OfficeTest (!(Test-Path -LiteralPath $path) -and $result.TestedDirectory -eq $testRoot -and @(Get-ChildItem -LiteralPath $testRoot -Force).Count -eq $before) 'Write checks must remove probes and never create deployment directories.' + $file = Join-Path $testRoot 'not-a-directory'; Set-Content -LiteralPath $file -Value 'fixture' + Assert-OfficeThrows { Assert-OfficeWritablePath $file } 'not a directory' + } + # Inspect persisted state without touching the actual registry or Office service. + & { + function Test-Path { return $true } + function Get-Item { [pscustomobject]@{PSPath='fixture';Name='ClickToRun'} } + function Get-ChildItem { } + function Get-Service { [pscustomobject]@{Name='ClickToRunSvc'} } + function Get-ItemProperty { [pscustomobject]@{WorkingConfiguration='old-guid';SourcePath='C:\Windows\SystemTemp\EmberkomOfficeDeployment\old\ODT';Platform='x64'} } + $state = Get-OfficeClickToRunState + Assert-OfficeTest ($state.Present -and $state.WorkingConfiguration[0] -eq 'old-guid' -and $state.SourceReferences.Count -eq 1) 'Interrupted Click-to-Run configuration must be detected without installed products.' + Assert-OfficeThrows { Assert-OfficeFreshInstallState } 'still retains previous deployment state.*Installation stopped.*old-guid' + function Get-ItemProperty { [pscustomobject]@{Platform='x64'} } + $null = Assert-OfficeFreshInstallState + function Get-ItemProperty { throw 'Registry access denied' } + Assert-OfficeThrows { Assert-OfficeFreshInstallState } 'Registry access denied' + } + # Execute the real deferred action with only its live download replaced. + & { + $id='d'*32; $script:liveHelperId=$null + function New-Object { + param($TypeName) + Assert-OfficeTest ($TypeName -eq 'Net.WebClient') 'Deferred cleanup must fetch its helper live.' + $client=[pscustomobject]@{} + $client | Add-Member ScriptMethod DownloadString { param($Uri) '# EmberkomOfficeUserCleanup-v5' + [Environment]::NewLine + 'param($DeploymentId) $script:liveHelperId=$DeploymentId' } + $client | Add-Member ScriptMethod Dispose { } + $client + } + $command=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String((New-OfficeUserCleanupCommand $id))) + & ([scriptblock]::Create($command)) + Assert-OfficeTest ($script:liveHelperId -eq $id -and !$command.Contains('-File ')) 'Deferred cleanup must execute freshly fetched source in memory with the correct deployment ID.' + } + # A new deployment clears every previous GUID workspace, including legacy caches, + # while preserving logs and refusing to race a previous installer or user task. + & { + $root=Join-Path $testRoot 'old-deployments'; $null=[IO.Directory]::CreateDirectory($root) + $old=Join-Path $root ('e'*32); $null=[IO.Directory]::CreateDirectory((Join-Path $old 'ODT')) + $legacyMetadata=Join-Path $testRoot ('OfficeReleaseHistory-' + ('e'*32) + '.html'); Set-Content -LiteralPath $legacyMetadata -Value 'abandoned metadata' + foreach ($name in @('ODT\payload.dat','ODT\native.log','install.xml','remove.xml','options.json','media-cache.json','Office-UserCleanup.ps1','user-cleanup.lock','reinstall-started','result.log')) { Set-Content -LiteralPath (Join-Path $old $name) -Value 'old content, not reusable' } + $unknown=Join-Path $root 'unrelated'; $null=[IO.Directory]::CreateDirectory($unknown); Set-Content -LiteralPath (Join-Path $unknown 'keep.txt') -Value 'untouched' + function Get-OfficeDeploymentRoots { $root } + $script:oldInstaller=$false; $script:oldTaskState='Running'; $script:oldTaskRemoved=$false + function Get-CimInstance { if ($script:oldInstaller) { [pscustomobject]@{Name='OfficeClickToRun.exe';CommandLine='OfficeClickToRun.exe platform=x64'} } } + function Get-ScheduledTask { if (!$script:oldTaskRemoved) { [pscustomobject]@{TaskName="Emberkom-OfficeCleanup-$('e'*32)-S-1-5-21-123";TaskPath='\';State=$script:oldTaskState} } } + function Disable-ScheduledTask { Assert-OfficeTest ($script:oldTaskState -eq 'Ready') 'Only idle tasks may be retired.' } + function Unregister-ScheduledTask { $script:oldTaskRemoved=$true } + Assert-OfficeThrows { Clear-OfficePreviousDeploymentFiles } 'user cleanup is still running' + Assert-OfficeTest (Test-Path -LiteralPath (Join-Path $old 'ODT\payload.dat')) 'Active user tasks must block old-cache cleanup.' + $script:oldTaskState='Ready'; $script:oldInstaller=$true + Assert-OfficeThrows { Clear-OfficePreviousDeploymentFiles } 'surviving installer' + $script:oldInstaller=$false + Clear-OfficePreviousDeploymentFiles + $remaining=@(Get-ChildItem -LiteralPath $old -Recurse -File) + Assert-OfficeTest ($script:oldTaskRemoved -and $remaining.Count -eq 2 -and @($remaining | Where-Object Extension -ne '.log').Count -eq 0) 'Previous cached downloads, options and scripts must be removed; nested logs must remain.' + Assert-OfficeTest (!(Test-Path -LiteralPath $legacyMetadata)) 'Abandoned legacy assessment metadata must be removed too.' + Assert-OfficeTest (Test-Path -LiteralPath (Join-Path $unknown 'keep.txt')) 'Cleanup must stay within GUID deployment folders.' + Clear-OfficePreviousDeploymentFiles + Assert-OfficeTest (@(Get-ChildItem -LiteralPath $old -Recurse -File).Count -eq 2) 'Cleanup must be repeatable with logs-only directories.' + } + # Cleanup runs synchronously on every install exit. Only logs survive in staging; + # pending-user tasks retain synchronization state but fetch their helper live. & { $root = Join-Path $testRoot 'temporary-downloads'; $null = [IO.Directory]::CreateDirectory($root) $workspace = Join-Path $root ('c' * 32); $null = [IO.Directory]::CreateDirectory($workspace) @@ -870,7 +957,7 @@ try { } $media = [pscustomobject]@{Helper=(Join-Path $workspace 'Office-UserCleanup.ps1')} $userWorkspace = New-OfficeUserWorkspace $media $workspace - Assert-OfficeTest ($media.Helper -eq (Join-Path $userWorkspace 'Office-UserCleanup.ps1') -and (Test-Path -LiteralPath $media.Helper)) 'User helper was not separated from staged installers.' + Assert-OfficeTest (!(Test-Path -LiteralPath (Join-Path $userWorkspace 'Office-UserCleanup.ps1')) -and (Test-Path -LiteralPath (Join-Path $userWorkspace 'user-cleanup.lock'))) 'Pending tasks must retain only synchronization state, never cached code.' $script:cleanupTasks = $true; $script:cleanupProcess = $true function Get-CimInstance { if ($script:cleanupProcess) { [pscustomobject]@{CommandLine="setup.exe $workspace\install.xml"} } } function Get-ScheduledTask { if ($script:cleanupTasks) { [pscustomobject]@{TaskName="Emberkom-OfficeCleanup-$('c' * 32)-SID"; State='Ready'} } } @@ -880,7 +967,8 @@ try { $script:cleanupProcess = $false $warnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath (Join-Path $workspace 'ODT')) -and !(Test-Path -LiteralPath (Join-Path $workspace 'odt.exe')) -and (Test-Path -LiteralPath (Join-Path $workspace 'office-install.stdout.log'))) 'Completion must remove media and preserve diagnostics.' - Assert-OfficeTest (Test-Path -LiteralPath $media.Helper) 'Temporary media cleanup deleted the pending-user helper.' + Assert-OfficeTest (!(Test-Path -LiteralPath $media.Helper) -and @(Get-ChildItem -LiteralPath $workspace -File | Where-Object Extension -ne '.log').Count -eq 0) 'Deployment cleanup must leave only log files.' + Assert-OfficeTest (Test-Path -LiteralPath (Join-Path $userWorkspace 'user-cleanup.lock')) 'Pending-user synchronization state must survive staging cleanup.' $script:cleanupTasks = $false $warnings = Complete-OfficeDeploymentFiles $workspace $userWorkspace Assert-OfficeTest (!$warnings.Count -and !(Test-Path -LiteralPath $userWorkspace)) 'Completed user cleanup left its helper folder behind.' @@ -922,6 +1010,11 @@ try { throw "Unexpected object requested by orchestration fixture: $TypeName" } function Assert-OfficeDeploymentHost { } + function Assert-OfficeWritablePath { param($Path) [pscustomobject]@{Path=$Path} } + function Test-OfficeDownloadLinks { [pscustomobject]@{StatusCode=200;Method='HEAD'} } + function Get-OfficeClickToRunState { [pscustomobject]@{Present=$false;SourceReferences=@();WorkingConfiguration=@()} } + function Clear-OfficePreviousDeploymentFiles { if ($script:mode -eq 'old-cache') { throw 'Previous artifacts are locked' }; $script:priorCleanupRuns++ } + function Assert-OfficeFreshInstallState { if ($script:mode -eq 'stale-state') { throw 'Previous Click-to-Run state remains' } } function Assert-OfficeDiskSpace { param($Workspace,[switch]$DownloadingMedia) if ($script:mode -eq 'preflight-space') { throw 'Insufficient disk space before download' }; if ($script:mode -eq 'disk-space' -and !$DownloadingMedia) { throw 'Insufficient disk space after staging' } } function Resolve-OfficeTargetVersion { if ($script:mode -eq 'release') { throw 'Release metadata unavailable' } } function Complete-OfficeDeploymentFiles { param($Workspace,$UserWorkspace) $script:artifactCleanupRuns++; if ($script:mode -eq 'download-cleanup') { throw 'Synthetic cleanup failure' }; if ($script:mode -eq 'cleanup-warning') { return ,@('Synthetic file in use') }; return ,@() } @@ -952,7 +1045,7 @@ try { function Install-OfficeCompanionApps { param($Media,$Workspace,[bool]$InstallTeams) $script:teamsRequested=$InstallTeams; $script:events += 'install-companions'; if ($script:mode -eq 'install-companions') { throw 'companion install failure' }; [pscustomobject]@{ExitCode=$(if ($script:mode -eq 'companion-reboot') {3010} else {0}); Versions=@{NewOutlook='1'; OneDrive='1'}} } $script:removalStillRegistered=$false $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Premium'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'; DeferReboot='false'} - foreach ($script:mode in @('success','download','download-cleanup','disk-space','companions','remove-office','identity','user','phase','install','install-companions','pending','reboot','office-reboot','companion-reboot')) { + foreach ($script:mode in @('success','download','download-cleanup','disk-space','companions','remove-office','stale-state','identity','user','phase','install','install-companions','pending','reboot','office-reboot','companion-reboot')) { $script:artifactCleanupRuns = 0 $script:events = @(); $errorResult = $null; $result = $null try { $result = Invoke-OfficeDeployment $options } catch { $errorResult = $_ } @@ -979,7 +1072,10 @@ try { $options.ValidateBeforeChanges=$false $script:mode='cleanup-warning'; $script:events=@() $result = @(Invoke-OfficeDeployment $options) - Assert-OfficeTest ($result.Count -eq 1 -and $result[0].ArtifactCleanupPending -and $result[0].ExitCode -eq 0 -and $result[0].OfficeDeploymentStatus -eq 'Installed') 'Artifact cleanup problems corrupted the receipt or failed a verified installation.' + Assert-OfficeTest ($result.Count -eq 1 -and $result[0].ArtifactCleanupPending -and $result[0].ExitCode -eq 2 -and $result[0].OfficeDeploymentStatus -eq 'InstalledWithArtifactCleanupPending') 'Unremoved artifacts must report partial completion instead of clean success.' + $script:mode='old-cache'; $script:events=@(); $script:workspaceCreates=0 + Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Previous artifacts are locked' + Assert-OfficeTest ($script:events.Count -eq 0 -and $script:workspaceCreates -eq 0) 'Old artifacts must be cleared before creating or downloading a new deployment.' foreach ($script:mode in @('registration','registration-and-pending','registration-reboot')) { $script:events=@(); $script:artifactCleanupRuns=0 function Install-OfficeMedia { $script:events += 'install'; if ($script:mode -eq 'registration-reboot') { return 3010 }; return 0 } @@ -1010,12 +1106,12 @@ try { Assert-OfficeTest (!$result.RestartRequired -and $result.ExitCode -eq 0) 'A clean deployment without restart requests must not demand a restart.' foreach ($shutdown in @('Abort','Force')) { foreach ($validate in @($null, '', 'true')) { - $script:events=@(); $script:workspaceCreates=0; $script:artifactCleanupRuns=0 + $script:events=@(); $script:workspaceCreates=0; $script:artifactCleanupRuns=0; $script:priorCleanupRuns=0 $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeAppShutdown=$shutdown; ValidateBeforeChanges=$validate} $result = Invoke-OfficeDeployment $options Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'ValidationPassed' -and $result.ExitCode -eq 0 -and $result.ValidateBeforeChanges) 'Validation did not produce a distinct result.' Assert-OfficeTest ($result.OfficeRemovalMethod -eq 'SilentODT' -and $result.DeferReboot -is [bool] -and $result.DeferReboot) 'Validation must identify the silent removal method and Boolean restart selection.' - Assert-OfficeTest ($script:events.Count -eq 0 -and $script:workspaceCreates -eq 0 -and $script:artifactCleanupRuns -eq 0 -and !$result.MediaDownloaded -and !$result.Workspace) 'Validation downloaded media, created a workspace or reached a deployment action.' + Assert-OfficeTest ($script:events.Count -eq 0 -and $script:workspaceCreates -eq 0 -and $script:artifactCleanupRuns -eq 0 -and $script:priorCleanupRuns -eq 0 -and !$result.MediaDownloaded -and !$result.Workspace -and !$result.MetadataResolved) 'Validation downloaded media, created a workspace or reached a deployment action.' Assert-OfficeTest (!$result.TeamsSelected -and $result.ProfileCount -eq 1 -and $result.ExistingOffice[0] -eq 'Synthetic Office') 'Validation report lost the deployment plan.' } } @@ -1028,8 +1124,11 @@ try { Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Apps are running' Assert-OfficeTest ($script:events.Count -eq 0) 'Validation did not stop on an Abort prerequisite failure.' $options.OfficeAppShutdown='Force'; $script:mode='release'; $script:events=@() + $result = Invoke-OfficeDeployment $options + Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'ValidationPassed' -and !$result.MetadataResolved) 'Assessment must not request release metadata.' + $options.ValidateBeforeChanges=$false Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Release metadata unavailable' - Assert-OfficeTest ($script:events.Count -eq 0) 'Failed validation reached media downloads or mutations.' + Assert-OfficeTest ($script:events.Count -eq 0) 'Failed release resolution reached media downloads or app removal.' $options.ValidateBeforeChanges='false' Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'validated Boolean' $options.ValidateBeforeChanges=$false; $options.DeferReboot='false'; $script:events=@() @@ -1120,8 +1219,10 @@ __LAUNCH__ Assert-OfficeTest ($probeExitCode -eq $case.Code) "Shim did not propagate workload exit $($case.Code): $probeOutput" $probeText = $probeOutput | Out-String if ($case.Mode -eq 'success') { - Assert-OfficeTest ($probeText.IndexOf('{') -ge 0) "Main workload receipt is missing from shim output: $probeText" - $receipt = $probeText.Substring($probeText.IndexOf('{')) | ConvertFrom-Json + # Temp/log paths can contain GUID braces; locate the JSON object's line. + $receiptStart = [regex]::Match($probeText, '(?m)^\s*\{\s*\r?$') + Assert-OfficeTest $receiptStart.Success "Main workload receipt is missing from shim output: $probeText" + $receipt = $probeText.Substring($receiptStart.Index) | ConvertFrom-Json Assert-OfficeTest ($receipt.ProductId -eq 'O365ProPlusEEANoTeamsRetail' -and $receipt.Company -ceq $probeValues.COMPANY -and $receipt.Activation -eq 'SharedComputer') 'Shim lost injected strings before main workload.' Assert-OfficeTest ($receipt.ValidateBeforeChanges -eq ($case.Validate -ne 'false')) 'Shim lost the validation gate.' Assert-OfficeTest ($receipt.DeferReboot -is [bool] -and !$receipt.DeferReboot) 'Shim/main entry lost or misparsed the injected false restart string.' @@ -1162,8 +1263,11 @@ exit $resultCode '@ $nativeProbePath = Join-Path $testRoot 'host-probe.ps1'; Set-Content -LiteralPath $nativeProbePath -Value $nativeProbeTemplate.Replace('__ENTRY__', $entryText) $x86PowerShell = Join-Path $env:WINDIR 'SysWOW64\WindowsPowerShell\v1.0\powershell.exe' + $ErrorActionPreference='Continue' $hostOutput = & $x86PowerShell -NoProfile -ExecutionPolicy Bypass -File $nativeProbePath 2>&1 - Assert-OfficeTest ($LASTEXITCODE -eq 2) '32-bit Syncro host lost the native-host exit code.' + $hostExitCode = $LASTEXITCODE + $ErrorActionPreference='Stop' + Assert-OfficeTest ($hostExitCode -eq 2) '32-bit Syncro host lost the native-host exit code.' $hostText = $hostOutput | Out-String Assert-OfficeTest ($hostText -match 'Native host probe' -and $hostText -notmatch 'CLIXML') 'Native host messages must remain readable in Syncro.' $hostResult = $hostText.Substring($hostText.IndexOf('{')) | ConvertFrom-Json