[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$LogPath, [Parameter(Mandatory = $true)] [string]$OutputPath, [ValidateRange(1, 3650)] [int]$Days = 30, [string]$Pattern = '*.log', [switch]$RemoveSource, [switch]$Force ) $ErrorActionPreference = 'Stop' Add-Type -AssemblyName System.IO.Compression.FileSystem if (-not (Test-Path -LiteralPath $LogPath -PathType Container)) { throw "Папка логов не найдена: $LogPath" } $logFull = (Resolve-Path -LiteralPath $LogPath).Path.TrimEnd([char[]]@([char]'\', [char]'/')) $outputFull = [IO.Path]::GetFullPath($OutputPath) if (Test-Path -LiteralPath $outputFull) { if (-not $Force) { throw "Файл уже существует: $outputFull. Используйте -Force" } Remove-Item -LiteralPath $outputFull -Force } $parent = Split-Path -Parent $outputFull if ($parent -and -not (Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null } $cutoff = (Get-Date).AddDays(-1 * $Days) $files = @(Get-ChildItem -LiteralPath $logFull -File -Recurse -Force | Where-Object { $_.Name -like $Pattern -and $_.LastWriteTime -lt $cutoff -and $_.FullName -ne $outputFull }) if ($files.Count -eq 0) { "Логи старше $Days дней не найдены." exit 0 } $stream = [IO.File]::Open($outputFull, [IO.FileMode]::CreateNew) $zip = [System.IO.Compression.ZipArchive]::new($stream, [System.IO.Compression.ZipArchiveMode]::Create) $count = 0 try { foreach ($file in $files) { $relative = $file.FullName.Substring($logFull.Length) $relative = $relative.TrimStart([char[]]@([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar)) $relative = $relative.Replace('\', '/') $entry = $zip.CreateEntry($relative, [System.IO.Compression.CompressionLevel]::Optimal) $entry.LastWriteTime = $file.LastWriteTime $input = [IO.File]::OpenRead($file.FullName) try { $output = $entry.Open() try { $input.CopyTo($output) } finally { $output.Dispose() } } finally { $input.Dispose() } $count++ } $entryCount = $zip.Entries.Count } finally { $zip.Dispose() $stream.Dispose() } if ($entryCount -ne $count) { throw "В архиве $entryCount элементов вместо $count" } $sizeMb = [math]::Round((Get-Item -LiteralPath $outputFull).Length / 1MB, 1) "Архив: $outputFull ($sizeMb МБ), файлов: $count" if ($RemoveSource) { foreach ($file in $files) { Remove-Item -LiteralPath $file.FullName -Force } "Исходные логи удалены: $($files.Count)" } else { "Исходные логи не изменялись. Для удаления добавьте -RemoveSource." }