Private/Invoke-WUEnhancedDiskCleanup.ps1

function Invoke-WUEnhancedDiskCleanup {
    <#
    .SYNOPSIS
        Performs enhanced disk cleanup to free space for Windows Updates.
 
    .DESCRIPTION
        Cleans temporary files, system caches, and performs WinSxS cleanup to ensure
        adequate disk space for Windows Update operations. Protects active log files
        including WindowsUpdateTools logs.
 
    .PARAMETER LogPath
        Path to the log file for detailed logging.
 
    .EXAMPLE
        $result = Invoke-WUEnhancedDiskCleanup -LogPath "C:\Logs\wu.log"
 
    .NOTES
        This is a private function used internally by the WindowsUpdateTools module.
        Returns an object with Success, SpaceFreed, and ActionsPerformed properties.
    #>


    [CmdletBinding()]
    param(
        [string]$LogPath
    )
    
    $result = [PSCustomObject]@{
        Success = $false
        SpaceFreed = 0
        ActionsPerformed = @()
    }
    
    try {
        Write-WULog -Message "Starting enhanced disk cleanup..." -LogPath $LogPath
        
        # Clean temp directories
        $tempPaths = @(
            "$env:TEMP\*",
            "$env:SystemRoot\Temp\*",
            "$env:SystemRoot\Prefetch\*",
            "$env:LocalAppData\Microsoft\Windows\INetCache\*"
        )
        
        foreach ($path in $tempPaths) {
            $items = Get-ChildItem -Path $path -Force -ErrorAction SilentlyContinue
            if ($items) {
                # Exclude current log file and other WindowsUpdateTools log files from cleanup
                $itemsToDelete = $items | Where-Object {
                    # Don't delete the current log file
                    if ($LogPath -and $_.FullName -eq $LogPath) { return $false }
                    
                    # Don't delete WindowsUpdateTools log files (WU-*.log)
                    if ($_.Name -match '^WU-.*\.log$') { return $false }
                    
                    # Don't delete files currently in use (basic check)
                    try {
                        [System.IO.FileStream] $stream = [System.IO.File]::Open($_.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
                        $stream.Close()
                        return $true  # File is not in use, safe to delete
                    }
                    catch {
                        return $false  # File is in use or protected, skip it
                    }
                }
                
                # Count protected files for logging
                $protectedFiles = $items | Where-Object {
                    ($LogPath -and $_.FullName -eq $LogPath) -or ($_.Name -match '^WU-.*\.log$')
                }
                
                $totalSize = ($itemsToDelete | Where-Object { -not $_.PSIsContainer } | Measure-Object -Property Length -Sum).Sum
                if ($itemsToDelete) {
                    Remove-Item -Path ($itemsToDelete.FullName) -Recurse -Force -ErrorAction SilentlyContinue
                    $result.SpaceFreed += $totalSize
                    $cleanedPath = Split-Path $path
                    $sizeMB = [math]::Round($totalSize / 1MB, 2)
                    $message = "Cleaned ${cleanedPath}: ${sizeMB} MB"
                    if ($protectedFiles.Count -gt 0) {
                        $message += " (protected $($protectedFiles.Count) log files)"
                    }
                    Write-WULog -Message $message -LogPath $LogPath
                }
            }
        }
        
        # WinSxS cleanup
        Write-WULog -Message "Performing WinSxS cleanup..." -LogPath $LogPath
        & DISM /Online /Cleanup-Image /StartComponentCleanup /ResetBase | Out-Null
        
        $result.ActionsPerformed += "Enhanced disk cleanup completed"
        $result.Success = $true
    }
    catch {
        Write-WULog -Message "Error during enhanced cleanup: $($_.Exception.Message)" -Level Warning -LogPath $LogPath
    }
    
    return $result
}