Архивы

Упаковать папку с исключениями

Создаёт zip через ZipArchive и пропускает кэши, логи и каталоги сборки по шаблонам.

PowerShell Windows Средний
Скачать Compress-Folder.ps1
Описание

Что делает скрипт

PowerShell сам обходит папку и добавляет записи в архив, поэтому можно гибко исключать файлы по относительному пути. Верхняя папка не добавляется, а пути внутри архива всегда используют прямой слеш. Существующий архив удаляется только с ключом -Force, а уровень сжатия выбирается явно.

Перед запуском
  • Существующий архив перезаписывается только с ключом -Force.
Запуск

Быстрый старт

powershell -File Compress-Folder.ps1 -SourcePath .\project -OutputPath .\project.zip

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.

Примеры

Другие варианты

  • powershell -File Compress-Folder.ps1 -SourcePath .\project -OutputPath .\project.zip
  • powershell -File Compress-Folder.ps1 -SourcePath .\project -OutputPath .\project.zip -Exclude '*.log','*\tmp\*'
  • powershell -File Compress-Folder.ps1 -SourcePath .\project -OutputPath .\project.zip -CompressionLevel Fastest -Force
Зависимости

Что понадобится

PowerShell 5.1+ Windows PowerShell или PowerShell 7
Windows Встроен в Windows 10/11 (PowerShell 5.1)
Исходник

Compress-Folder.ps1

[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [string]$SourcePath,
    [Parameter(Mandatory = $true)]
    [string]$OutputPath,
    [string[]]$Exclude = @('*.tmp', '*.log', '.git\*', '*\.git\*', 'node_modules\*', '*\node_modules\*', '__pycache__\*', '*\__pycache__\*', '.venv\*', '*\.venv\*'),
    [ValidateSet('Optimal', 'Fastest', 'NoCompression')]
    [string]$CompressionLevel = 'Optimal',
    [switch]$Force
)

$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.IO.Compression.FileSystem

if (-not (Test-Path -LiteralPath $SourcePath -PathType Container)) {
    throw "Папка не найдена: $SourcePath"
}
$sourceFull = (Resolve-Path -LiteralPath $SourcePath).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
}

$level = [System.Enum]::Parse([System.IO.Compression.CompressionLevel], $CompressionLevel)
$files = @(Get-ChildItem -LiteralPath $sourceFull -File -Recurse -Force | Where-Object { $_.FullName -ne $outputFull })
if ($files.Count -eq 0) {
    throw "В папке нет файлов"
}

$stream = [IO.File]::Open($outputFull, [IO.FileMode]::CreateNew)
$zip = [System.IO.Compression.ZipArchive]::new($stream, [System.IO.Compression.ZipArchiveMode]::Create)
$count = 0
$skipped = 0
try {
    foreach ($file in $files) {
        $relative = $file.FullName.Substring($sourceFull.Length)
        $relative = $relative.TrimStart([char[]]@([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar))
        $relative = $relative.Replace('\', '/')
        $relativeWindows = $relative.Replace('/', '\')
        $excluded = $false
        foreach ($pattern in $Exclude) {
            if ($relative -like $pattern -or $relativeWindows -like $pattern) {
                $excluded = $true
                break
            }
        }
        if ($excluded) {
            $skipped++
            continue
        }
        $entry = $zip.CreateEntry($relative, $level)
        $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++
    }
} finally {
    $zip.Dispose()
    $stream.Dispose()
}

if ($count -eq 0) {
    Remove-Item -LiteralPath $outputFull -Force
    throw "После исключений не осталось файлов"
}
"Добавлено файлов: $count, исключено: $skipped"
"Готово: $outputFull"

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get archives-compress-folder-exclude
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Архивы

Упаковка, распаковка, проверка целостности и безопасная работа с архивами.