[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] param( [switch]$Apply ) $ErrorActionPreference = 'Stop' $download = Join-Path $env:SystemRoot 'SoftwareDistribution\Download' if (-not (Test-Path -LiteralPath $download -PathType Container)) { throw "Каталог не найден: $download" } $items = @(Get-ChildItem -LiteralPath $download -Force -Recurse -ErrorAction SilentlyContinue) $bytes = ($items | Measure-Object -Property Length -Sum).Sum if ($null -eq $bytes) { $bytes = 0 } Write-Host ("Каталог: {0}" -f $download) Write-Host ("Объектов: {0}, объём: {1:N1} MB" -f $items.Count, ($bytes / 1MB)) if (-not $Apply) { Write-Host 'Предпросмотр. С -Apply содержимое Download будет удалено при остановленных службах.' return } $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = New-Object Security.Principal.WindowsPrincipal($identity) if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Для очистки кэша обновлений нужны права администратора.' } $stopped = @() try { foreach ($name in @('wuauserv', 'bits')) { $service = Get-Service -Name $name -ErrorAction SilentlyContinue if ($null -ne $service -and $service.Status -eq 'Running') { Stop-Service -Name $name -Force -ErrorAction Stop $stopped += $name Write-Host "Служба остановлена: $name" } } if ($PSCmdlet.ShouldProcess($download, 'Очистить кэш обновлений Windows')) { Get-ChildItem -LiteralPath $download -Force -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue Write-Host 'Содержимое Download очищено.' } } finally { foreach ($name in $stopped) { Start-Service -Name $name -ErrorAction SilentlyContinue Write-Host "Служба запущена: $name" } } $remaining = @(Get-ChildItem -LiteralPath $download -Force -Recurse -ErrorAction SilentlyContinue) $remainingBytes = ($remaining | Measure-Object -Property Length -Sum).Sum if ($null -eq $remainingBytes) { $remainingBytes = 0 } Write-Host ("После очистки: {0:N1} MB" -f ($remainingBytes / 1MB))