[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] param( [string]$Path = ".", [ValidateRange(1, 3650)] [int]$OlderThanDays = 30, [switch]$Remove, [switch]$Force ) $ErrorActionPreference = 'Stop' $root = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).Path if (-not (Test-Path -LiteralPath $root -PathType Container)) { throw "Folder not found: $root" } if ($Remove -and -not $Force) { throw "Remove requires -Force because environment folders will be deleted." } $candidates = Get-ChildItem -LiteralPath $root -Directory -Recurse -Depth 3 -ErrorAction SilentlyContinue | Where-Object { Test-Path -LiteralPath (Join-Path $_.FullName 'pyvenv.cfg') -PathType Leaf } $rows = @() foreach ($folder in $candidates) { $config = Join-Path $folder.FullName 'pyvenv.cfg' $version = '' try { $line = Select-String -LiteralPath $config -Pattern '^version\s*=\s*(.+)$' -ErrorAction SilentlyContinue | Select-Object -First 1 if ($line) { $version = $line.Matches[0].Groups[1].Value.Trim() } } catch { $version = '' } $size = 0 try { $sum = Get-ChildItem -LiteralPath $folder.FullName -File -Recurse -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum if ($sum.Sum) { $size = [double]$sum.Sum } } catch { $size = 0 } $age = [math]::Floor(((Get-Date) - $folder.LastWriteTime).TotalDays) $active = ($env:VIRTUAL_ENV -and ([System.IO.Path]::GetFullPath($env:VIRTUAL_ENV) -eq $folder.FullName)) $rows += [pscustomobject]@{ Path = $folder.FullName Python = $version SizeMB = [math]::Round($size / 1MB, 1) AgeDays = $age Old = ($age -ge $OlderThanDays) Active = $active } } if ($rows.Count -eq 0) { Write-Host "No virtual environments found." exit 0 } $rows | Sort-Object @{ Expression = 'Old'; Descending = $true }, @{ Expression = 'SizeMB'; Descending = $true } | Format-Table -AutoSize if (-not $Remove) { Write-Host "Report only. Use -Remove -Force to delete selected environments." exit 0 } $removed = 0 foreach ($row in $rows) { if ($row.Active) { Write-Host "Skip active environment: $($row.Path)" continue } if ($PSCmdlet.ShouldProcess($row.Path, "Remove virtual environment")) { Remove-Item -LiteralPath $row.Path -Recurse -Force $removed++ Write-Host "Removed: $($row.Path)" } } Write-Host "Removed environments: $removed"