Архивировать старые логи
Собирает логи старше заданного срока в zip и при необходимости удаляет исходники.
Что делает скрипт
Скрипт выбирает файлы по маске и дате изменения, сохраняет относительные пути и сначала создаёт архив. Удаление исходников выполняется только с ключом -RemoveSource и только после успешной записи. По умолчанию ничего не удаляется, поэтому результат можно проверить.
- Исходные логи удаляются только с ключом -RemoveSource.
- Перед удалением проверяется, что архив записан.
Быстрый старт
powershell -File Archive-OldLogs.ps1 -LogPath .\logs -OutputPath .\logs-2025.zip -Days 30
Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.
Другие варианты
powershell -File Archive-OldLogs.ps1 -LogPath .\logs -OutputPath .\logs-2025.zip -Days 30powershell -File Archive-OldLogs.ps1 -LogPath C:\app\logs -OutputPath C:\backup\logs.zip -Days 90powershell -File Archive-OldLogs.ps1 -LogPath .\logs -OutputPath .\logs.zip -Days 30 -RemoveSource
Что понадобится
Встроен в Windows 10/11 (PowerShell 5.1)
Archive-OldLogs.ps1
[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."
}
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.