Перепаковать zip с другим сжатием
Создаёт копию zip с выбранным уровнем сжатия и возможностью выбросить лишние элементы.
Что делает скрипт
Скрипт читает исходный архив и пишет новый через ZipArchive, не меняя оригинал. Можно выбрать Optimal, Fastest или NoCompression и исключить элементы по шаблонам. Небезопасные имена пропускаются, поэтому в новый архив не попадут пути с .. или диском.
- Исходный архив не изменяется.
- Существующий выходной файл перезаписывается только с ключом -Force.
Быстрый старт
powershell -File Repack-Zip.ps1 -InputPath .\old.zip -OutputPath .\new.zip
Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.
Другие варианты
powershell -File Repack-Zip.ps1 -InputPath .\old.zip -OutputPath .\new.zippowershell -File Repack-Zip.ps1 -InputPath .\old.zip -OutputPath .\new.zip -CompressionLevel Fastestpowershell -File Repack-Zip.ps1 -InputPath .\old.zip -OutputPath .\new.zip -Exclude '*.log' -Force
Что понадобится
Встроен в Windows 10/11 (PowerShell 5.1)
Repack-Zip.ps1
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$InputPath,
[Parameter(Mandatory = $true)]
[string]$OutputPath,
[ValidateSet('Optimal', 'Fastest', 'NoCompression')]
[string]$CompressionLevel = 'Optimal',
[string[]]$Exclude = @(),
[switch]$Force
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.IO.Compression.FileSystem
if (-not (Test-Path -LiteralPath $InputPath -PathType Leaf)) {
throw "Архив не найден: $InputPath"
}
$inputFull = (Resolve-Path -LiteralPath $InputPath).Path
$outputFull = [IO.Path]::GetFullPath($OutputPath)
if ($inputFull -eq $outputFull) {
throw "Вход и выход совпадают"
}
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
}
$level = [System.Enum]::Parse([System.IO.Compression.CompressionLevel], $CompressionLevel)
$source = [IO.Compression.ZipFile]::OpenRead($inputFull)
$stream = [IO.File]::Open($outputFull, [IO.FileMode]::CreateNew)
$target = [System.IO.Compression.ZipArchive]::new($stream, [System.IO.Compression.ZipArchiveMode]::Create)
$copied = 0
$skipped = 0
try {
foreach ($entry in $source.Entries) {
$name = $entry.FullName.Replace('\', '/')
if ([string]::IsNullOrWhiteSpace($name)) { continue }
if ($name.StartsWith('/') -or $name -match '^[A-Za-z]:' -or $name.Contains(':') -or $name -match '(^|/)\.\.(/|$)') {
Write-Warning "Пропуск небезопасного пути: $($entry.FullName)"
$skipped++
continue
}
$excluded = $false
foreach ($pattern in $Exclude) {
if ($name -like $pattern -or $entry.Name -like $pattern) {
$excluded = $true
break
}
}
if ($excluded) {
$skipped++
continue
}
$newEntry = $target.CreateEntry($name, $level)
$newEntry.LastWriteTime = $entry.LastWriteTime
if ($entry.Name -eq '' -or $name.EndsWith('/')) {
$copied++
continue
}
$input = $entry.Open()
try {
$output = $newEntry.Open()
try {
$input.CopyTo($output)
} finally {
$output.Dispose()
}
} finally {
$input.Dispose()
}
$copied++
}
} finally {
$target.Dispose()
$stream.Dispose()
$source.Dispose()
}
"Перенесено элементов: $copied, пропущено: $skipped"
"Готово: $outputFull"
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.