[CmdletBinding()] param( [ValidateRange(1, 365)] [int]$OlderThanDays = 7, [switch]$Apply, [switch]$Force ) $ErrorActionPreference = 'Stop' $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = New-Object Security.Principal.WindowsPrincipal($identity) if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Нужны права администратора: запустите PowerShell от имени администратора.' } $download = Join-Path $env:SystemRoot 'SoftwareDistribution\Download' if (-not (Test-Path -LiteralPath $download -PathType Container)) { Write-Host "Папка кэша не найдена: $download" return } $cutoff = (Get-Date).AddDays(-$OlderThanDays) $files = @(Get-ChildItem -LiteralPath $download -Recurse -File -Force -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt $cutoff }) $total = 0 if ($files.Count -gt 0) { $total = ($files | Measure-Object -Property Length -Sum).Sum } Write-Host ("Папка: {0}" -f $download) Write-Host ("Файлов старше {0} дней: {1}, объём: {2} МБ" -f $OlderThanDays, $files.Count, [math]::Round($total / 1MB, 2)) if ($files.Count -eq 0) { Write-Host 'Нечего очищать.' return } $files | Sort-Object Length -Descending | Select-Object -First 20 @{Name = 'SizeMB'; Expression = { [math]::Round($_.Length / 1MB, 2) }}, LastWriteTime, FullName | Format-Table -AutoSize if (-not $Apply) { Write-Host 'Это предпросмотр. Для очистки добавьте -Apply.' return } if (-not $Force) { $answer = Read-Host 'Введите yes, чтобы остановить службы и удалить эти файлы' if ($answer -ne 'yes') { Write-Host 'Отменено.' return } } $services = @('wuauserv', 'bits') $stopped = New-Object System.Collections.Generic.List[string] foreach ($name in $services) { $service = Get-Service -Name $name -ErrorAction SilentlyContinue if ($null -ne $service -and $service.Status -eq 'Running') { try { Stop-Service -Name $name -Force -ErrorAction Stop $stopped.Add($name) Write-Host "Служба остановлена: $name" } catch { Write-Warning "Не удалось остановить службу ${name}: $_" } } } $removed = 0 $failed = 0 try { Get-ChildItem -LiteralPath $download -Force -ErrorAction SilentlyContinue | ForEach-Object { try { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction Stop $removed++ } catch { $failed++ Write-Warning "Пропуск $($_.FullName): $_" } } } finally { foreach ($name in $stopped) { try { Start-Service -Name $name -ErrorAction Stop Write-Host "Служба запущена: $name" } catch { Write-Warning "Не удалось запустить службу ${name}: $_" } } } Write-Host "Удалено объектов: $removed, пропущено: $failed" Write-Host 'Кэш обновлений очищен. Следующая проверка обновлений загрузит нужные файлы заново.'