[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] param( [switch]$Apply ) $ErrorActionPreference = 'Stop' $roots = @( $env:LOCALAPPDATA, (Join-Path $env:LOCALAPPDATA 'Programs') ) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -Unique $pattern = '^(?.+?)[-_ ]v?(?\d+(?:\.\d+){1,3})$' $groups = @{} foreach ($root in $roots) { $directories = Get-ChildItem -LiteralPath $root -Directory -Force -ErrorAction SilentlyContinue foreach ($directory in $directories) { if ($directory.Name -notmatch $pattern) { continue } $appName = $Matches['app'] $versionText = $Matches['version'] try { $version = [version]$versionText } catch { continue } $key = "$root|$appName" if (-not $groups.ContainsKey($key)) { $groups[$key] = @() } $groups[$key] += [pscustomobject]@{ App = $appName Version = $version VersionText = $versionText Path = $directory.FullName Modified = $directory.LastWriteTime } } } $candidates = @() foreach ($key in $groups.Keys) { $list = @($groups[$key] | Sort-Object -Property Version -Descending) if ($list.Count -lt 2) { continue } for ($index = 1; $index -lt $list.Count; $index++) { $old = $list[$index] $bytes = ( Get-ChildItem -LiteralPath $old.Path -File -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum ).Sum if ($null -eq $bytes) { $bytes = 0 } $candidates += [pscustomobject]@{ App = $old.App OldVersion = $old.VersionText NewVersion = $list[0].VersionText SizeMB = [math]::Round($bytes / 1MB, 1) Path = $old.Path Modified = $old.Modified } } } $candidates = @($candidates | Sort-Object -Property App, OldVersion) if ($candidates.Count -eq 0) { Write-Host 'Старые версии приложений не найдены.' return } Write-Host ("Каталогов старых версий: {0}" -f $candidates.Count) $candidates | Format-Table App, OldVersion, NewVersion, SizeMB, Path -AutoSize if (-not $Apply) { Write-Host 'Предпросмотр. Для удаления старых версий добавьте -Apply.' return } $removed = 0 $failed = 0 foreach ($candidate in $candidates) { $allowed = $false foreach ($root in $roots) { if ($candidate.Path.StartsWith($root, [System.StringComparison]::OrdinalIgnoreCase)) { $allowed = $true break } } if (-not $allowed) { Write-Warning "Пропуск пути вне LocalAppData: $($candidate.Path)" continue } if ($PSCmdlet.ShouldProcess($candidate.Path, "Удалить старую версию $($candidate.OldVersion)")) { try { Remove-Item -LiteralPath $candidate.Path -Recurse -Force -ErrorAction Stop $removed++ Write-Host "Удалено: $($candidate.Path)" } catch { $failed++ Write-Warning "Не удалось удалить $($candidate.Path): $($_.Exception.Message)" } } } Write-Host "Удалено: $removed, ошибок: $failed"