[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] param( [string]$Path = $env:USERPROFILE, [ValidateRange(0, 3650)] [int]$Days = 30, [switch]$Apply ) $ErrorActionPreference = 'Stop' if (-not (Test-Path -LiteralPath $Path -PathType Container)) { throw "Каталог не найден: $Path" } $resolved = (Resolve-Path -LiteralPath $Path).ProviderPath.TrimEnd('\') if ($resolved -eq ([System.IO.Path]::GetPathRoot($resolved)).TrimEnd('\')) { throw 'Нельзя использовать корень диска.' } if ($resolved.StartsWith($env:SystemRoot, [System.StringComparison]::OrdinalIgnoreCase)) { throw 'Нельзя использовать системный каталог Windows.' } $cutoff = (Get-Date).AddDays(-$Days) $files = @( Get-ChildItem -LiteralPath $resolved -File -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { $_.Name -match '\.log(\.\d+)?(\.gz)?$' -and $_.LastWriteTime -lt $cutoff } ) $bytes = ($files | Measure-Object -Property Length -Sum).Sum if ($null -eq $bytes) { $bytes = 0 } Write-Host ("Старых журналов: {0}, объём: {1:N1} MB" -f $files.Count, ($bytes / 1MB)) $files | Select-Object Name, Length, LastWriteTime, FullName | Format-Table -AutoSize 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"