adds OfficeStaging and SystemTemp

This commit is contained in:
2026-10-23 12:25:00 -04:00
parent f9daec0542
commit e2163a6158
4 changed files with 229 additions and 9 deletions
+105 -2
View File
@@ -20,6 +20,7 @@ function Get-SystemCleanupDefaults {
CleanupDiagnosticDays = 30
CleanupBackupDays = 30
CleanupSystemTemp = $true
CleanupOfficeStaging = $true
CleanupUserTemp = $true
CleanupServiceTemp = $true
CleanupCBSArchives = $true
@@ -183,7 +184,9 @@ function Get-SystemCleanupChildren {
Write-SystemCleanupMessage "Skipping linked or unsafe path: $Root"
return
}
Get-ChildItem -LiteralPath $Root -Force -ErrorAction Stop | Where-Object { -not ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) }
# Office staging has its own mutex/identity/retention rules. Generic temp scans
# must not bypass them or remove deferred user-cleanup helpers.
Get-ChildItem -LiteralPath $Root -Force -ErrorAction Stop | Where-Object { -not ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -and $_.Name -ne 'EmberkomOfficeDeployment' }
}
function Get-SystemCleanupFiles {
@@ -201,6 +204,7 @@ function Get-SystemCleanupFiles {
function Remove-SystemCleanupFile {
param($Context, [string]$Category, [string]$Root, [string]$Path, [datetime]$Cutoff)
if ($Category -ne 'OfficeStaging' -and $Path -match '(?i)(^|[\\/])EmberkomOfficeDeployment([\\/]|$)') { return }
if (-not (Test-SystemCleanupPath $Path $Root)) { return }
$file = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
if ($file.PSIsContainer -or $file.LastWriteTimeUtc -ge $Cutoff) { return }
@@ -533,6 +537,100 @@ function Remove-SystemCleanupBundle {
}
}
function Get-SystemCleanupOfficeStagingRoots {
param([string[]]$Profiles)
@(
(Join-Path ([IO.Path]::GetTempPath()) 'EmberkomOfficeDeployment')
(Join-Path $env:SystemRoot 'Temp\EmberkomOfficeDeployment')
(Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment')
(Join-Path $env:ProgramData 'EmberkomOfficeDeployment')
foreach ($profile in $Profiles) { Join-Path $profile 'AppData\Local\Temp\EmberkomOfficeDeployment' }
) | Sort-Object -Unique
}
function New-SystemCleanupOfficeMutex {
return New-Object Threading.Mutex($false, 'Global\EmberkomOfficeDeployment')
}
function Clear-SystemCleanupOfficeStaging {
param($Context, [string[]]$Roots, [datetime]$Cutoff)
$rootsPresent = @($Roots | Select-Object -Unique | Where-Object { Test-Path -LiteralPath $_ })
if (-not $rootsPresent.Count) { return }
$mutex = New-SystemCleanupOfficeMutex
$acquired = $false; $retained = 0
try {
try { $acquired = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $acquired = $true }
if (-not $acquired) { Set-SystemCleanupSkipped $Context 'OfficeStaging' 'Office deployment is running; staging retained.'; return }
$processes = @(Get-CimInstance Win32_Process -ErrorAction Stop)
if (@($processes | Where-Object { $_.Name -in @('setup.exe', 'odt.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe') }).Count) {
Set-SystemCleanupSkipped $Context 'OfficeStaging' 'An installer is running; staging retained.'; return
}
# Match Install-MicrosoftOffice365's disposable artifact allowlist. Never delete
# options, logs, XML, user helpers, task markers, locks or the workspace itself.
$names = @('ODT', 'odt.exe', 'odt-download-page.html', 'GetHelp', 'GetHelp.zip', 'media-cache.json',
'MicrosoftEdgeWebview2Setup.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe')
foreach ($root in $rootsPresent) {
if (-not (Test-SystemCleanupPath $root $root)) { $retained++; continue }
foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -Force -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' })) {
try {
if (-not (Test-SystemCleanupPath $folder.FullName $root)) { throw 'Linked or unsafe workspace.' }
$markerPath = Join-Path $folder.FullName 'options.json'
if (-not (Test-Path -LiteralPath $markerPath -PathType Leaf)) { throw 'Missing deployment identity.' }
if (-not (Test-SystemCleanupPath $markerPath $root)) { throw 'Linked deployment identity.' }
$marker = Get-Item -LiteralPath $markerPath -Force -ErrorAction Stop
if ($marker.Length -gt 64KB) { throw 'Oversized deployment identity.' }
$options = Get-Content -LiteralPath $markerPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
if ($options.ProductId -notin @('O365BusinessRetail','O365BusinessEEANoTeamsRetail','O365ProPlusRetail','O365ProPlusEEANoTeamsRetail') -or
$options.OfficeArchitecture -notin @('32','64') -or $options.UpdateChannel -notin @('Current','MonthlyEnterprise','SemiAnnual')) { throw 'Unrecognized deployment identity.' }
if ($folder.LastWriteTimeUtc -ge $Cutoff -or $marker.LastWriteTimeUtc -ge $Cutoff) { throw 'Recent deployment.' }
foreach ($process in $processes) {
foreach ($value in @($process.CommandLine, $process.ExecutablePath)) {
if ($value -and $value.IndexOf($folder.FullName, [StringComparison]::OrdinalIgnoreCase) -ge 0) { throw 'Workspace is referenced by a running process.' }
}
}
$items = New-Object 'System.Collections.Generic.List[object]'
$pending = New-Object 'System.Collections.Generic.Stack[string]'
foreach ($name in $names) {
$target = Join-Path $folder.FullName $name
if (Test-Path -LiteralPath $target) { $pending.Push($target) }
}
while ($pending.Count) {
$target = $pending.Pop()
if (-not (Test-SystemCleanupPath $target $folder.FullName)) { throw 'Linked staging artifact.' }
$item = Get-Item -LiteralPath $target -Force -ErrorAction Stop
if ($item.LastWriteTimeUtc -ge $Cutoff) { throw 'Recent staging artifact.' }
$items.Add($item)
if ($item.PSIsContainer) {
foreach ($child in @(Get-ChildItem -LiteralPath $target -Force -ErrorAction Stop)) { $pending.Push($child.FullName) }
} else {
# Probe in preview too; in-use data is not an eligible estimate.
$probe = [IO.File]::Open($item.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
$probe.Dispose()
}
}
foreach ($file in @($items | Where-Object { -not $_.PSIsContainer })) {
Remove-SystemCleanupFile $Context 'OfficeStaging' $folder.FullName $file.FullName $Cutoff
}
if (-not $Context.Options.ReportOnly) {
foreach ($directory in @($items | Where-Object PSIsContainer | Sort-Object { $_.FullName.Length } -Descending)) {
if ((Test-SystemCleanupPath $directory.FullName $folder.FullName) -and @(Get-ChildItem -LiteralPath $directory.FullName -Force -ErrorAction Stop).Count -eq 0) {
[IO.Directory]::Delete($directory.FullName, $false)
}
}
}
} catch {
$retained++
Write-SystemCleanupMessage "Office staging retained at $($folder.FullName): $($_.Exception.Message)" -Detail
}
}
}
if ($retained) { $Context.Stats.OfficeStaging.Notes = "$retained folder(s) retained: recent, active, unrecognized or unsafe; see verbose." }
} finally {
if ($acquired) { $mutex.ReleaseMutex() }
$mutex.Dispose()
}
}
function Get-SystemCleanupRecycleDate {
param([string]$MetadataPath)
if ((Get-Item -LiteralPath $MetadataPath -Force -ErrorAction Stop).Length -gt 1MB) { throw 'Oversized Recycle Bin metadata.' }
@@ -700,9 +798,14 @@ function Invoke-SystemCleanup {
# Generic temp cleaning must not bypass the AutoCAD process check or dump retention.
$tempExclusions = @('*.ac$', '*.sv$', '*.dmp')
Invoke-SystemCleanupCategory $context 'SystemTemp' {
Clear-SystemCleanupTree $context 'SystemTemp' (Join-Path $env:SystemRoot 'Temp') $tempCutoff -Exclude $tempExclusions -Recurse
foreach ($relative in @('Temp', 'SystemTemp')) {
Clear-SystemCleanupTree $context 'SystemTemp' (Join-Path $env:SystemRoot $relative) $tempCutoff -Exclude $tempExclusions -Recurse
}
# Includes .evtx, computer-name logs, AppxErrorReport files, and Chocolatey temp.
}
Invoke-SystemCleanupCategory $context 'OfficeStaging' {
Clear-SystemCleanupOfficeStaging $context (Get-SystemCleanupOfficeStagingRoots $allProfiles) $tempCutoff
}
Invoke-SystemCleanupCategory $context 'UserTemp' {
$acadRunning = Test-SystemCleanupAppRunning @('acad')
foreach ($profile in $profiles) {