diff --git a/Install-MicrosoftOffice365.ps1 b/Install-MicrosoftOffice365.ps1 index 6c82795..17bc55a 100644 --- a/Install-MicrosoftOffice365.ps1 +++ b/Install-MicrosoftOffice365.ps1 @@ -84,6 +84,13 @@ function Get-OfficeDeploymentDefinitions { UserCleanupWaitMinutes = 20 UserCleanupTaskMinutes = 30 MediaCacheDays = 7 + # Deployment headroom, not Microsoft's published minimum system requirements. + # Reserve installation/companion space in addition to a fresh media download. + MinimumInstallFreeSpaceGB = 10 + MediaDownloadReserveGB = 6 + SetupDiagnosticFileLimit = 8 + SetupDiagnosticTailLines = 2000 + SetupDiagnosticErrorLines = 12 } } @@ -256,6 +263,36 @@ function Get-OfficeStagingNames { foreach ($installer in (Get-OfficeDeploymentDefinitions).CompanionInstallers.Values) { $installer.File } } +function Assert-OfficeDiskSpace { + param( + [string]$Workspace, + [switch]$DownloadingMedia, + [string[]]$InstallPaths = @($env:WINDIR, $env:ProgramFiles, ${env:ProgramFiles(x86)}) + ) + $definitions = Get-OfficeDeploymentDefinitions + $required = @{} + foreach ($path in @($InstallPaths | Where-Object { $_ })) { + $drive = [IO.Path]::GetPathRoot([IO.Path]::GetFullPath($path)).TrimEnd('\') + $required[$drive] = [long]($definitions.MinimumInstallFreeSpaceGB * 1GB) + } + if ($DownloadingMedia) { + $stageDrive = [IO.Path]::GetPathRoot([IO.Path]::GetFullPath($Workspace)).TrimEnd('\') + $required[$stageDrive] = [long]$required[$stageDrive] + [long]($definitions.MediaDownloadReserveGB * 1GB) + } + foreach ($drive in ($required.Keys | Sort-Object)) { + if ($drive -notmatch '^[A-Za-z]:$') { throw "Office deployment requires a local drive for disk-space checks: $drive" } + $disk = Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='$drive'" -ErrorAction Stop + if ($null -eq $disk -or $null -eq $disk.FreeSpace) { throw "Could not determine free space on $drive. Existing apps have not been removed." } + $availableGB = [Math]::Round(([long]$disk.FreeSpace / 1GB), 2) + $requiredGB = [Math]::Round(($required[$drive] / 1GB), 2) + $stage = if ($DownloadingMedia) { 'before downloading media' } else { 'after staging, before removal' } + $null = Write-Output "Office disk-space check ${stage}: $drive has $availableGB GB free; deployment requires $requiredGB GB." + if ([long]$disk.FreeSpace -lt $required[$drive]) { + throw "Insufficient disk space on $drive ${stage}: $availableGB GB free; at least $requiredGB GB required. Free space and rerun. Existing apps have not been removed. Staged media remains in $Workspace." + } + } +} + function Remove-OfficeStagingFiles { param([string]$Root, [string]$Workspace) Assert-OfficeManagedPath $Root $Workspace @@ -439,9 +476,16 @@ function Invoke-OfficeProcess { for ($attempt = 1; ; $attempt++) { $prefix = if ($attempt -eq 1) { $LogPrefix } else { "$LogPrefix.retry-$attempt" } $null = Write-Output "Running: $FilePath $Arguments. Process logs: $prefix" + $startedUtc = [DateTime]::UtcNow $process = Start-Process -FilePath $FilePath -ArgumentList $Arguments -WorkingDirectory (Split-Path -Parent $FilePath) -Wait -PassThru -WindowStyle Hidden -RedirectStandardOutput "$prefix.stdout.log" -RedirectStandardError "$prefix.stderr.log" -ErrorAction Stop if ($null -eq $process.ExitCode) { throw "No exit code returned from $FilePath." } $null = Write-Output "Process exited $($process.ExitCode): $FilePath" + if ([IO.Path]::GetFileName($FilePath) -ieq 'setup.exe' -and $process.ExitCode -notin @(0, 3010)) { + # ODT normally writes details to native temp logs, not stdout/stderr. + # Diagnostic collection must never replace the installer's original result. + try { Write-OfficeSetupDiagnostics -SinceUtc $startedUtc } + catch { $null = Write-Output "Could not collect native Office diagnostics: $($_.Exception.Message)" } + } # Retry only MSI's documented busy result, not arbitrary installer failures. if (!$isMsi -or $process.ExitCode -ne 1618 -or $attempt -ge $definitions.MsiBusyAttempts) { return [int]$process.ExitCode } $null = Write-Output "Windows Installer is busy; retrying in $($definitions.MsiBusyRetrySeconds) seconds (attempt $attempt of $($definitions.MsiBusyAttempts))." @@ -449,6 +493,40 @@ function Invoke-OfficeProcess { } } +function Write-OfficeSetupDiagnostics { + param( + [DateTime]$SinceUtc, + [string[]]$SearchRoots = @([IO.Path]::GetTempPath(), "$env:WINDIR\Temp", "$env:WINDIR\SystemTemp") + ) + $definitions = Get-OfficeDeploymentDefinitions + $finishedUtc = [DateTime]::UtcNow + $files = @(foreach ($root in ($SearchRoots | Select-Object -Unique)) { + try { + if (!(Test-Path -LiteralPath $root -PathType Container)) { continue } + Get-ChildItem -LiteralPath $root -Filter '*.log' -File -ErrorAction Stop | Where-Object { + $_.Length -gt 0 -and $_.LastWriteTimeUtc -ge $SinceUtc.AddSeconds(-5) -and $_.LastWriteTimeUtc -le $finishedUtc -and + !($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -and + ($_.Name -like "$env:COMPUTERNAME-*.log" -or $_.Name -match '^(Office|Microsoft[ _-]*Office|ClickToRun|Setup)') + } + } catch { $null = Write-Output "Could not search native Office logs in ${root}: $($_.Exception.Message)" } + }) + $files = @($files | Sort-Object FullName -Unique | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First $definitions.SetupDiagnosticFileLimit) + if (!$files.Count) { + $null = Write-Output "No recent nonempty native Office logs found in: $($SearchRoots -join '; '). Empty ODT stdout/stderr files do not contain the underlying setup error." + return + } + foreach ($file in $files) { + $null = Write-Output "Native Office log: $($file.FullName) ($($file.Length) bytes). Recent matching lines below are diagnostic clues, not an automatic diagnosis." + try { + $lines = @(Get-Content -LiteralPath $file.FullName -Tail $definitions.SetupDiagnosticTailLines -ErrorAction Stop | + Where-Object { $_ -match '(?i)\b(error|failed|failure|exception|unexpected)\b|"Error(Code|Type|Message|Details)"' } | + Select-Object -Last $definitions.SetupDiagnosticErrorLines) + if (!$lines.Count) { $null = Write-Output 'No error-like lines found in the inspected tail; retain the full native log for diagnosis.' } + foreach ($line in $lines) { $null = Write-Output "Native Office detail: $line" } + } catch { $null = Write-Output "Could not read native Office log $($file.FullName): $($_.Exception.Message)" } + } +} + function Wait-OfficeResult { param([scriptblock]$Probe, [string]$Description) # A probe returns a verified value/true, or nothing/false while registration catches up. @@ -542,6 +620,7 @@ function Initialize-OfficeMedia { $cached | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $Workspace 'media-cache.json') -Encoding UTF8 -ErrorAction Stop return [pscustomobject]@{ Setup=(Join-Path $odtFolder 'setup.exe'); RemovalConfig=$removalPath; Config=$configPath; Helper=$helper; Version=$cached.Version; Companions=$companions; CachedMediaReused=$true } } + Assert-OfficeDiskSpace -Workspace $Workspace -DownloadingMedia $pagePath = Join-Path $Workspace 'odt-download-page.html' Save-OfficeDownload $definitions.OdtPage $pagePath -TimeoutSeconds $definitions.OdtPageTimeoutSeconds $url = Get-OfficeOdtDownloadUrl (Get-Content -LiteralPath $pagePath -Raw -ErrorAction Stop) @@ -981,7 +1060,7 @@ function Install-OfficeMedia { param($Options, $Media, [string]$Workspace) $msi = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 }) $code = Invoke-OfficeProcess $Media.Setup "/configure `"$($Media.Config)`"" (Join-Path $Workspace 'office-install') - if ($code -notin @(0, 3010)) { throw "Office installation failed (exit $code). Media and logs remain in $Workspace. If old Office needs repair, arrange an attended manual scrub: $((Get-OfficeDeploymentDefinitions).ManualScrubUrl). No interactive scrubber was launched." } + if ($code -notin @(0, 3010)) { throw "Office installation failed (exit $code). Media and logs remain in $Workspace. Review the Native Office log/detail entries in the diagnostic log; Click-to-Run writes its underlying errors to the execution account's temp folder or Windows\Temp. The exit code alone does not identify the cause. No interactive scrubber was launched." } $msiRemoved = Wait-OfficeResult { @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 }).Count -eq 0 } 'legacy MSI Office removal by ODT' if (!$msiRemoved) { $remaining = @(Get-OfficeSuiteInventory | Where-Object { $_.WindowsInstaller -eq 1 }) @@ -1033,6 +1112,9 @@ function Invoke-OfficeDeployment { if (!(Test-Path -LiteralPath (Join-Path $profile.LocalPath 'NTUSER.DAT'))) { throw "Profile $($profile.SID) is unavailable. Mount its profile/container before deploying." } } $media = Initialize-OfficeMedia $Options $workspace + # Also check cache hits: a successful download does not prove enough space + # remains to expand Office and install the selected companion apps. + Assert-OfficeDiskSpace -Workspace $workspace if ($Options.ValidateBeforeChanges) { $existingOffice = @(Get-OfficeSuiteInventory | ForEach-Object { $_.DisplayName }) # This helper is refreshed on every run; validation does not need to retain it. diff --git a/docs/Office365-Deployment.md b/docs/Office365-Deployment.md index f9ac317..00ee6d3 100644 --- a/docs/Office365-Deployment.md +++ b/docs/Office365-Deployment.md @@ -64,6 +64,8 @@ With `ValidateBeforeChanges=true`, the script checks the subscription/activation Validation writes logs and staging files in the execution account's temp directory, secures its workspace, and runs ODT extraction and `/download` when no reusable cache exists; it is not a zero-write inventory scan. Allow several GB for the first run. It registers no scheduled tasks. A later `false` run repeats prerequisites and reuses matching, unexpired media after checking its file inventory, sizes, and Microsoft executable signatures. The script does not calculate or compare file checksums. The small user cleanup helper is always refreshed from the repository and is deleted from the validation workspace before returning. Validation does not prove tenant entitlements, successful future uninstallation/activation, or availability of the online companion payloads at install time. +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:, this means 16 GB free before a fresh download and 10 GB remaining after staging. A cache hit only needs the installation reserve. Windows and Program Files volumes are checked separately when they differ. Both validation and deployment check again after staging, before app shutdown/removal, so a completed download cannot pass validation with too little space left to install. These are adjustable deployment headroom values in `Get-OfficeDeploymentDefinitions`, not Microsoft's minimum system requirements or a guarantee against concurrent disk use. A space failure reports the drive, available space, and requirement; it preserves staged media for reuse after space is freed. It does not delete unrelated files or add housekeeping tasks. + The script resolves the current versioned ODT download from the [Microsoft Download Center](https://www.microsoft.com/en-us/download/details.aspx?id=49117). It does not depend on the Emberkom-hosted setup.exe or a frozen Microsoft binary URL. If the page format changes, it stops before removal. The downloaded ODT package and extracted setup.exe must have valid Microsoft signatures. **Unattended deployment does not download or launch Get Help.** The Get Help build observed on October 14, 2026 created an elevated PowerShell cleanup window in the logged-in user's session even when its parent ran hidden under SYSTEM. Hiding the parent did not hide that child, and Microsoft's documented `-HideProgress` option applies to other scenarios, not Office removal. See the [Get Help command-line reference](https://learn.microsoft.com/en-us/troubleshoot/microsoft-365/admin/miscellaneous/get-help-command-line-overview). The script uses ODT's supported silent removal instead; an interactive scrub is an attended troubleshooting step only. @@ -152,6 +154,10 @@ Earlier ProgramData caches are not searched for reuse in the new temp location. Syncro may flag nonzero results as errors; read the printed status, pending SIDs, and task registration failures. Schedule any required restart separately. The script also returns `3010` after verified legacy MSI Office removal, following Microsoft's restart requirement. +ODT's redirected `stdout`/`stderr` files can be empty even when installation fails. Microsoft writes native setup/Click-to-Run logs in the execution account's temp directory and `C:\Windows\Temp`; SYSTEM's temp may be `C:\Windows\SystemTemp`. On an ODT failure, the script searches those folders for recent, nonempty Office/setup or computer-name logs and appends bounded error excerpts and their full paths to the existing Tools diagnostic log. Look for `Native Office log:` and `Native Office detail:`. Collection is read-only, creates no task or additional resident helper, and cannot override the original installer exit code. Excerpts are clues; retain the full native logs when diagnosing a failure. + +Exit `17004` is documented as `ERROR_COMPLETING_SCENARIO_NEED_CLEAN_UP`, with possible reasons including unknown SKUs or unavailable CDN content. It does not establish that an old Office installation needs a scrub. Inspect the native error details before changing removal behavior or repeating a destructive deployment. See [Microsoft's Office CSP error table](https://learn.microsoft.com/en-us/windows/client-management/mdm/office-csp) and [ODT troubleshooting log locations](https://learn.microsoft.com/en-us/microsoft-365-apps/deploy/deploy-microsoft-365-apps-local-source). + If machine companion removal still fails verification, the error identifies the remaining component, version, and registry location, along with the uninstall log folder. The main log also records which add-in registrations were left to user cleanup. An uninstall exit code of `1605` alone does not establish that all users' installations are gone; Windows Installer context determines which stage handles the add-in. This failure occurs before Office removal, identity reset, and reinstallation, but companion apps may already have been removed. The main script uses the overridden `Write-Output` and `Write-Error` from `Tools.ps1` for actions, retries, failures, and the final receipt, writing to its existing `$Global:LogFile`. Internal action messages suppress the logger's echoed success output to keep function results separate from diagnostics. The mode notice, log location, and final receipt use `Microsoft.PowerShell.Utility\Write-Output` for Syncro. Errors are logged and also printed to Syncro. Native PowerShell relaunch reloads Tools and restores the caller's log path. Run the core through the shim/Tools execution context, not as an independent file without Tools. diff --git a/tests/Install-MicrosoftOffice365.Tests.ps1 b/tests/Install-MicrosoftOffice365.Tests.ps1 index fb10b81..772fa91 100644 --- a/tests/Install-MicrosoftOffice365.Tests.ps1 +++ b/tests/Install-MicrosoftOffice365.Tests.ps1 @@ -37,7 +37,38 @@ try { # Exercise the real bounded retry loops without delaying offline tests. function Start-Sleep { param([int]$Seconds) $script:testSleeps += $Seconds } function Get-FileHash { throw 'Office deployment must not scan file checksums.' } + $diskSpaceCheck = ${function:Assert-OfficeDiskSpace} + # Staging/orchestration fixtures must not depend on this test computer's free space. + function Assert-OfficeDiskSpace { param($Workspace,[switch]$DownloadingMedia) } $script:testSleeps = @() + & { + function Get-CimInstance { + param($ClassName,$Filter) + Assert-OfficeTest ($ClassName -eq 'Win32_LogicalDisk') 'Disk checks must use read-only logical-disk inventory.' + $script:diskQueries += $Filter + if ($script:diskReadFails) { throw 'Synthetic disk inventory failure' } + if ($Filter -match "DeviceID='([^']+)'") { [pscustomobject]@{FreeSpace=$script:freeBytes[$Matches[1]]} } + } + $script:diskReadFails=$false; $script:diskQueries=@() + $script:freeBytes=@{'C:'=16GB; 'D:'=6GB; 'E:'=10GB} + $output = @(& $diskSpaceCheck -Workspace 'C:\Temp\Office' -InstallPaths @('C:\Windows','C:\Program Files') -DownloadingMedia) + Assert-OfficeTest ($output.Count -eq 0 -and $script:diskQueries.Count -eq 1) 'A shared staging/install volume must combine reserves once without leaking log messages.' + $script:freeBytes['C:']=16GB-1 + Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'C:\Temp\Office' -InstallPaths @('C:\Windows') -DownloadingMedia } 'Insufficient disk space.*before downloading media.*16 GB.*Existing apps have not been removed' + $script:freeBytes['C:']=10GB + $null = & $diskSpaceCheck -Workspace 'C:\Temp\Office' -InstallPaths @('C:\Windows') + $script:freeBytes['C:']=1701MB + Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'C:\Temp\Office' -InstallPaths @('C:\Windows') } 'Insufficient disk space.*after staging, before removal' + $script:freeBytes['C:']=10GB; $script:diskQueries=@() + $null = & $diskSpaceCheck -Workspace 'D:\Temp\Office' -InstallPaths @('C:\Windows','E:\Program Files') -DownloadingMedia + Assert-OfficeTest ($script:diskQueries.Count -eq 3) 'Separate staging, Windows, and application drives must each be checked.' + $script:freeBytes['D:']=5GB + Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'D:\Temp\Office' -InstallPaths @('C:\Windows') -DownloadingMedia } 'Insufficient disk space on D:.*6 GB' + $script:freeBytes['C:']=$null + Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'D:\Temp\Office' -InstallPaths @('C:\Windows') } 'Could not determine free space' + $script:diskReadFails=$true + Assert-OfficeThrows { & $diskSpaceCheck -Workspace 'D:\Temp\Office' -InstallPaths @('C:\Windows') } 'Synthetic disk inventory failure' + } & { $script:probeCalls=0; $script:testSleeps=@() $result = Wait-OfficeResult { $script:probeCalls++; if ($script:probeCalls -eq 3) { [pscustomobject]@{Version='ready'} } } 'delayed fixture registration' @@ -50,6 +81,12 @@ try { Assert-OfficeTest ($script:probeCalls -eq 1) 'Failed inventory reads must not be treated as absent installations.' } & { + function Write-OfficeSetupDiagnostics { + param($SinceUtc) + $script:diagnosticCalls++ + Assert-OfficeTest ($SinceUtc -is [DateTime]) 'ODT diagnostics must use the actual process start time.' + if ($script:diagnosticFails) { throw 'Synthetic locked diagnostic log' } + } function Start-Process { param($FilePath,$ArgumentList,$WorkingDirectory,[switch]$Wait,[switch]$PassThru,$WindowStyle,$RedirectStandardOutput,$RedirectStandardError) $script:processCalls++; $script:processLogs += $RedirectStandardOutput @@ -68,6 +105,43 @@ try { Assert-OfficeTest ($code -eq $expectedCode -and $script:processCalls -eq $expectedCalls -and $script:testSleeps.Count -eq ($expectedCalls - 1)) "Incorrect retry behavior for $mode." Assert-OfficeTest (@($script:processLogs | Select-Object -Unique).Count -eq $expectedCalls) 'MSI retry output logs must not overwrite earlier attempts.' } + foreach ($script:diagnosticFails in @($false, $true)) { + $script:processExit=17004; $script:diagnosticCalls=0 + $output = @(Invoke-OfficeProcess (Join-Path $testRoot 'setup.exe') '/configure inert.xml' (Join-Path $testRoot 'odt-failed')) + Assert-OfficeTest ($output.Count -eq 1 -and $output[0] -eq 17004 -and $script:diagnosticCalls -eq 1) 'ODT native diagnostic collection must retain the original exit code and not pollute output, even when collection fails.' + } + $script:diagnosticFails=$false + foreach ($script:processExit in @(0,3010)) { + $script:diagnosticCalls=0 + $null = Invoke-OfficeProcess (Join-Path $testRoot 'setup.exe') '/configure inert.xml' (Join-Path $testRoot 'odt-success') + Assert-OfficeTest ($script:diagnosticCalls -eq 0) 'Successful ODT operations must not search unrelated native logs.' + } + } + & { + $nativeRoot = Join-Path $testRoot 'native-logs'; $null = [IO.Directory]::CreateDirectory($nativeRoot) + $since = [DateTime]::UtcNow.AddMinutes(-1) + $recent = Join-Path $nativeRoot ($env:COMPUTERNAME + '-20261022-test.log') + [IO.File]::WriteAllLines($recent, @('Normal setup entry', 'Click-To-Run Error {"ErrorCode":12345,"ErrorMessage":"Synthetic setup reason"}')) + $old = Join-Path $nativeRoot 'Office-old.log'; [IO.File]::WriteAllText($old, 'Error Old unrelated failure'); [IO.File]::SetLastWriteTimeUtc($old, $since.AddHours(-1)) + $unrelated = Join-Path $nativeRoot 'OtherApplication.log'; [IO.File]::WriteAllText($unrelated, 'Error Unrelated app failure') + $empty = Join-Path $nativeRoot 'Office-empty.log'; [IO.File]::WriteAllText($empty, '') + $nested = Join-Path $nativeRoot 'nested'; $null = [IO.Directory]::CreateDirectory($nested) + [IO.File]::WriteAllText((Join-Path $nested 'Office-nested.log'), 'Error Nested unrelated failure') + $output = @(Write-OfficeSetupDiagnostics -SinceUtc $since -SearchRoots @($nativeRoot,$nativeRoot)) + Assert-OfficeTest ($output.Count -eq 0) 'Native diagnostics must write through Tools logging without leaking return values.' + $log = Get-Content -LiteralPath $Global:LogFile -Raw + Assert-OfficeTest ($log -match 'Synthetic setup reason' -and $log.Contains($recent)) 'The management log must include the native filename and actual error detail.' + Assert-OfficeTest (([regex]::Matches($log, 'Native Office detail:.*Synthetic setup reason')).Count -eq 1) 'Duplicate search roots must not duplicate diagnostics.' + Assert-OfficeTest ($log -notmatch 'Old unrelated failure|Unrelated app failure|Nested unrelated failure|Office-empty.log') 'Diagnostics must exclude old, unrelated, empty, and nested logs.' + Assert-OfficeTest ((Get-Content -LiteralPath $recent -Raw) -match 'Normal setup entry') 'Collecting native diagnostics must not modify the original log.' + [IO.File]::WriteAllLines($recent, @(1..30 | ForEach-Object { "Error Bounded native detail $_" })) + $null = Write-OfficeSetupDiagnostics -SinceUtc $since -SearchRoots @($nativeRoot) + $log = Get-Content -LiteralPath $Global:LogFile -Raw + Assert-OfficeTest (([regex]::Matches($log, 'Native Office detail: Error Bounded native detail')).Count -eq (Get-OfficeDeploymentDefinitions).SetupDiagnosticErrorLines) 'Native error excerpts must be bounded.' + $null = Write-OfficeSetupDiagnostics -SinceUtc ([DateTime]::UtcNow.AddMinutes(1)) -SearchRoots @($nativeRoot) + Assert-OfficeTest ((Get-Content -LiteralPath $Global:LogFile -Raw) -match 'No recent nonempty native Office logs found') 'Missing native logs must be reported without inventing a diagnosis.' + function Get-Content { throw 'Synthetic native log read failure' } + Assert-OfficeTest (@(Write-OfficeSetupDiagnostics -SinceUtc $since -SearchRoots @($nativeRoot)).Count -eq 0) 'A locked native log must not throw or alter the installer result.' } & { function Invoke-WebRequest { @@ -336,6 +410,12 @@ try { Assert-OfficeTest (([xml](Get-Content -LiteralPath $media.Config -Raw)).Configuration.Add.Version -eq $media.Version) 'Windows 10 installation must retain the compatible target.' } } + $mediaWorkspace = Join-Path $testRoot 'low-space-before-download'; $null = [IO.Directory]::CreateDirectory($mediaWorkspace) + $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft 365 Business Standard'; OfficeArchitecture='64'} + $script:mediaProcesses=@() + function Assert-OfficeDiskSpace { param($Workspace,[switch]$DownloadingMedia) Assert-OfficeTest $DownloadingMedia.IsPresent 'A fresh download must include staging space.'; throw 'Synthetic insufficient download space' } + Assert-OfficeThrows { Initialize-OfficeMedia $options $mediaWorkspace } 'Synthetic insufficient download space' + Assert-OfficeTest (!$script:mediaProcesses.Count -and !(Test-Path -LiteralPath (Join-Path $mediaWorkspace 'odt.exe'))) 'Low space must stop before downloading or launching ODT.' } & { $script:staged = @(); $script:verified = @() @@ -763,6 +843,7 @@ try { $options = Get-OfficeDeploymentOptions @{OfficeSubscription='Microsoft/Office 365 E3/E5 (no Teams)'; OfficeArchitecture='64'; COMPANY='New Company'; OfficeAppShutdown='Force'; ValidateBeforeChanges='false'} $script:rejectCacheSignature = $false; $script:helperDownloads = 0 function Get-CimInstance { } + function Assert-OfficeDiskSpace { throw 'Cache reuse must not request fresh-download disk reserve; the main workflow checks installation space afterward.' } function Assert-OfficeMicrosoftSignature { param($Path) if ($script:rejectCacheSignature) { throw 'Untrusted cache signature' }; Assert-OfficeTest (Test-Path -LiteralPath $Path) 'Cache signature target was missing.' } function Save-OfficeDownload { param($Uri,$Path) if ([IO.Path]::GetFileName($Path) -ne 'Office-UserCleanup.ps1') { throw 'Unexpected network download on cache hit' }; $script:helperDownloads++; Set-Content -LiteralPath $Path -Value ('# ' + (Get-OfficeDeploymentDefinitions).HelperVersion) } function Invoke-OfficeProcess { throw 'A cached deployment must not redownload Office.' } @@ -892,6 +973,7 @@ try { throw "Unexpected object requested by orchestration fixture: $TypeName" } function Assert-OfficeDeploymentHost { } + function Assert-OfficeDiskSpace { param($Workspace,[switch]$DownloadingMedia) if ($script:mode -eq 'disk-space') { throw 'Insufficient disk space after staging' } } function Complete-OfficeDeploymentFiles { param($Workspace,$UserWorkspace,$PreviousRoot) $script:artifactCleanupRuns++; if ($script:mode -eq 'cleanup-warning') { return ,@('Synthetic file in use') }; return ,@() } function New-OfficeUserWorkspace { param($Media,$Workspace) $Workspace } function Register-ScheduledTask { throw 'Unexpected task registration in orchestration fixture.' } @@ -920,7 +1002,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','companions','remove-office','identity','user','phase','install','install-companions','pending','reboot','office-reboot','companion-reboot')) { + foreach ($script:mode in @('success','download','disk-space','companions','remove-office','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 = $_ } @@ -932,10 +1014,15 @@ try { if ($script:mode -notin @('success','pending','install','install-companions','companion-reboot')) { Assert-OfficeTest ('install' -notin $script:events) "Install ran after $script:mode failure/reboot." } if ($script:mode -notin @('success','pending','install-companions','companion-reboot')) { Assert-OfficeTest ('install-companions' -notin $script:events) "Companion install ran after $script:mode failure/reboot." } if ($script:mode -eq 'download') { Assert-OfficeTest ('companions' -notin $script:events -and 'remove-office' -notin $script:events) 'Removal ran after download failed.' } + if ($script:mode -eq 'disk-space') { Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Low space after staging must stop before app shutdown, removal, identity cleanup, and installation.' } Assert-OfficeTest ($script:artifactCleanupRuns -eq $(if ($script:mode -in @('success','pending','companion-reboot')) {1} else {0})) "Media cleanup ran before successful installation, or was skipped after success: $script:mode" if ($script:mode -eq 'office-reboot') { Assert-OfficeTest ($result.OfficeDeploymentStatus -eq 'RestartRequiredBeforeInstall' -and 'identity' -notin $script:events -and 'user' -notin $script:events) 'Office removal restart must stop before user cleanup and replacement installation.' } if ($script:mode -eq 'success') { Assert-OfficeTest (($script:events -join ',') -eq 'download,apps,companions,remove-office,identity,user,phase,install,install-companions') 'Deployment order changed.' } } + $script:mode='disk-space'; $script:events=@(); $options.ValidateBeforeChanges=$true + Assert-OfficeThrows { Invoke-OfficeDeployment $options } 'Insufficient disk space after staging' + Assert-OfficeTest (($script:events -join ',') -eq 'download') 'Validation must not report success or mutate apps with insufficient installation space.' + $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.'