add checks for free disk space

This commit is contained in:
2026-10-22 16:57:31 -04:00
parent 0030be0c7b
commit c8eec20391
3 changed files with 177 additions and 2 deletions
+83 -1
View File
@@ -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.