[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] param( [string]$Path = $env:TEMP, [ValidateRange(0, 3650)] [int]$Days = 7, [ValidateRange(0, 1048576)] [int]$MinSizeMB = 0, [switch]$Apply, [string]$Csv ) $ErrorActionPreference = 'Stop' if (-not (Test-Path -LiteralPath $Path -PathType Container)) { throw "Каталог не найден: $Path" } $resolved = (Resolve-Path -LiteralPath $Path).ProviderPath.TrimEnd('\') $tempRoot = (Resolve-Path -LiteralPath $env:TEMP).ProviderPath.TrimEnd('\') if (-not ($resolved -eq $tempRoot -or $resolved.StartsWith($tempRoot + '\', [System.StringComparison]::OrdinalIgnoreCase))) { throw "Скрипт работает только внутри пользовательского TEMP: $tempRoot" } $cutoff = (Get-Date).AddDays(-$Days) $files = @( Get-ChildItem -LiteralPath $resolved -File -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt $cutoff -and ($_.Length / 1MB) -ge $MinSizeMB } ) $total = ($files | Measure-Object -Property Length -Sum).Sum if ($null -eq $total) { $total = 0 } Write-Host ("Файлов старше {0} дней: {1}, объём: {2:N1} MB" -f $Days, $files.Count, ($total / 1MB)) if ($files.Count -gt 0) { $files | Sort-Object -Property Length -Descending | Select-Object -First 20 @{Name = 'SizeMB'; Expression = { [math]::Round($_.Length / 1MB, 2) } }, LastWriteTime, FullName | Format-Table -AutoSize } if ($Csv) { $files | Select-Object FullName, Length, LastWriteTime | Export-Csv -LiteralPath $Csv -NoTypeInformation -Encoding UTF8 Write-Host "Отчёт сохранён: $Csv" } if (-not $Apply) { Write-Host 'Предпросмотр. Для удаления добавьте -Apply.' return } $removed = 0 $failed = 0 foreach ($file in $files) { if ($PSCmdlet.ShouldProcess($file.FullName, 'Удалить временный файл')) { try { Remove-Item -LiteralPath $file.FullName -Force -ErrorAction Stop $removed++ } catch { $failed++ Write-Warning "Не удалось удалить $($file.FullName): $($_.Exception.Message)" } } } Write-Host "Удалено: $removed, ошибок: $failed"