Private/System/Invoke-ResourceDisposal.ps1
|
#Requires -Version 5.1 function Invoke-ResourceCleanup { <# .SYNOPSIS Performs comprehensive resource cleanup and disposal .DESCRIPTION Executes resource cleanup including object disposal, memory cleanup, and resource finalization following community best practices for PowerShell resource management. .PARAMETER MemoryManager MemoryManager instance to dispose .PARAMETER AdditionalResources Additional IDisposable resources to dispose .PARAMETER CorrelationId Correlation identifier for tracking cleanup operations .EXAMPLE PS> Invoke-ResourceCleanup -MemoryManager $memoryManager Disposes memory manager and performs cleanup .EXAMPLE PS> Invoke-ResourceCleanup -MemoryManager $memoryManager -AdditionalResources @($resource1, $resource2) Disposes multiple resources safely .NOTES WHATIF BEHAVIOR: - Resource disposal operations ALWAYS execute regardless of -WhatIf - Only detailed logging operations respect -WhatIf - This ensures critical cleanup is not skipped during simulations TROUBLESHOOTING: - For disposal issues: .\Troubleshooting\Performance\Memory-Management-Issues.md - For performance: .\Troubleshooting\Performance\Performance-Tuning.md #> [CmdletBinding(SupportsShouldProcess)] param( [Parameter()] [AllowNull()] [MemoryManager]$MemoryManager, [Parameter()] [AllowNull()] [System.IDisposable[]]$AdditionalResources, [Parameter()] [string]$CorrelationId = [System.Guid]::NewGuid().ToString() ) begin { # Ensure correlation ID is not empty if (-not $CorrelationId.Trim()) { $CorrelationId = [System.Guid]::NewGuid().ToString() } } process { try { # Resource disposal operations always execute - critical for system stability # Only detailed logging respects ShouldProcess if ($PSCmdlet.ShouldProcess("Resources", "Dispose and cleanup")) { Write-StructuredLog "Starting resource cleanup and disposal..." -Level Information -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId } else { Write-Verbose "WhatIf: Would dispose and cleanup resources" Write-StructuredLog "WhatIf simulation: resource disposal would be performed" -Level Debug -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId } # ALWAYS dispose resources - essential for system stability regardless of WhatIf # Dispose additional resources first if ($AdditionalResources) { foreach ($resource in $AdditionalResources) { if ($resource -and $resource -is [System.IDisposable]) { try { $resource.Dispose() if ($PSCmdlet.ShouldProcess("Resources", "Log additional resource disposal")) { Write-StructuredLog "Additional resource disposed successfully" -Level Debug -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId } } catch { Write-StructuredLog "Failed to dispose additional resource: $($_.Exception.Message)" -Level Warning -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId } } } } # Dispose memory manager if ($MemoryManager -and (-not $MemoryManager.Disposed)) { try { $MemoryManager.Dispose() if ($PSCmdlet.ShouldProcess("Resources", "Log memory manager disposal")) { Write-StructuredLog "Memory manager disposed successfully" -Level Information -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId } } catch { Write-StructuredLog "Failed to dispose memory manager: $($_.Exception.Message)" -Level Warning -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId } } # Perform final memory cleanup - always execute try { [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() [System.GC]::Collect() if ($PSCmdlet.ShouldProcess("Resources", "Log final garbage collection")) { Write-StructuredLog "Final garbage collection completed" -Level Debug -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId } } catch { Write-StructuredLog "Final garbage collection failed: $($_.Exception.Message)" -Level Warning -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId } } catch { Write-StructuredLog "Resource cleanup operation failed: $($_.Exception.Message)" -Level Error -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId $message = "Resource cleanup failed: $($_.Exception.Message)" $exception = [System.InvalidOperationException]::new($message, $_.Exception) $category = [System.Management.Automation.ErrorCategory]::InvalidOperation $errorRecord = [System.Management.Automation.ErrorRecord]::new( $exception, 'ResourceCleanupFailed', $category, $null) $PSCmdlet.ThrowTerminatingError($errorRecord) } } end { Write-StructuredLog "Resource cleanup completed" -Level Information -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId } } # Functions are automatically available when dot-sourced # Note: Export-ModuleMember is only valid in .psm1 module files |