Modules/businessdev.ALbuild.Core/Private/Invoke-ALbuildModulePrune.ps1
|
function Invoke-ALbuildModulePrune { <# .SYNOPSIS Keep only the newest N installed businessdev.ALbuild version folders; delete older ones. .DESCRIPTION A shared account/module root grows a new side-by-side version per publish and the old bootstrap never pruned - SRV05 had accumulated 52. Called INSIDE the install mutex so it never races an install. Only well-formed version folders are pruning candidates; parked '*.defekt-*' folders are exempt (R8) so a broken version is kept for post-mortem. .PARAMETER ModuleDir The '…\Modules\businessdev.ALbuild' folder holding the per-version subfolders. .PARAMETER KeepVersions Number of newest versions to retain (>= 1). .OUTPUTS System.String[] - the versions removed. #> [CmdletBinding(SupportsShouldProcess)] [OutputType([string[]])] param( [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $ModuleDir, [Parameter(Mandatory)] [ValidateRange(1, [int]::MaxValue)] [int] $KeepVersions ) if (-not (Test-Path -LiteralPath $ModuleDir)) { return @() } # Candidates: child folders whose name is a valid version. This excludes '*.defekt-*' (does not parse) # and any staging residue. $versions = @(Get-ChildItem -LiteralPath $ModuleDir -Directory -ErrorAction SilentlyContinue | ForEach-Object { $v = $null if ([version]::TryParse($_.Name, [ref]$v)) { [PSCustomObject]@{ Version = $v; Dir = $_.FullName } } } | Sort-Object Version -Descending) if ($versions.Count -le $KeepVersions) { return @() } $removed = New-Object System.Collections.Generic.List[string] foreach ($old in $versions[$KeepVersions..($versions.Count - 1)]) { if ($PSCmdlet.ShouldProcess($old.Dir, 'Prune old businessdev.ALbuild version')) { try { Remove-Item -LiteralPath $old.Dir -Recurse -Force -ErrorAction Stop; $removed.Add("$($old.Version)") } catch { Write-ALbuildLog -Level Warning "Could not prune '$($old.Dir)': $($_.Exception.Message)" } } } if ($removed.Count -gt 0) { Write-ALbuildLog "Pruned $($removed.Count) old businessdev.ALbuild version(s): $($removed -join ', ')." } , $removed.ToArray() } |