Архивы

Архивировать конфигурации

Собирает json, yaml, ini, conf и другие файлы настроек в zip с manifest и без ключей.

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

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

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

Перед запуском
  • Скрипт пропускает очевидные файлы с секретами, но архив всё равно нужно проверить перед отправкой.
Запуск

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

powershell -File Archive-Configs.ps1 -SourcePath .\app -OutputPath .\configs.zip

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

Примеры

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

  • powershell -File Archive-Configs.ps1 -SourcePath .\app -OutputPath .\configs.zip
  • powershell -File Archive-Configs.ps1 -SourcePath C:\app -OutputPath C:\backup\configs.zip -Force
  • powershell -File Archive-Configs.ps1 -SourcePath .\app -OutputPath .\configs.zip -Include '*.json','*.yaml'
Зависимости

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

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

Archive-Configs.ps1

[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [string]$SourcePath,
    [Parameter(Mandatory = $true)]
    [string]$OutputPath,
    [string[]]$Include = @('*.json', '*.yaml', '*.yml', '*.toml', '*.ini', '*.cfg', '*.conf', '*.config', '*.xml', '*.properties', '*.env.example'),
    [string[]]$Exclude = @('*.key', '*.pem', '*.pfx', '*.p12', '*.secret', 'id_rsa*', 'id_ed25519*', '.env'),
    [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
}

$skipDirs = '(^|[\\/])(\.git|\.hg|\.svn|node_modules|\.venv|venv|__pycache__|dist|build)([\\/]|$)'
$selected = New-Object System.Collections.ArrayList
foreach ($file in Get-ChildItem -LiteralPath $sourceFull -File -Recurse -Force) {
    if ($file.FullName -eq $outputFull) { continue }
    $relative = $file.FullName.Substring($sourceFull.Length)
    $relative = $relative.TrimStart([char[]]@([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar))
    $relative = $relative.Replace('\', '/')
    if ($relative -match $skipDirs) { continue }
    $included = $false
    foreach ($pattern in $Include) {
        if ($file.Name -like $pattern) {
            $included = $true
            break
        }
    }
    if (-not $included) { continue }
    $blocked = $false
    foreach ($pattern in $Exclude) {
        if ($file.Name -like $pattern -or $relative -like $pattern) {
            $blocked = $true
            break
        }
    }
    if ($blocked) { continue }
    [void]$selected.Add([pscustomobject]@{ File = $file; Relative = $relative })
}

if ($selected.Count -eq 0) {
    "Подходящие файлы конфигурации не найдены."
    exit 0
}

$stream = [IO.File]::Open($outputFull, [IO.FileMode]::CreateNew)
$zip = [System.IO.Compression.ZipArchive]::new($stream, [System.IO.Compression.ZipArchiveMode]::Create)
try {
    $lines = New-Object System.Collections.ArrayList
    [void]$lines.Add("source=$sourceFull")
    [void]$lines.Add("created=$((Get-Date).ToString('yyyy-MM-dd HH:mm:ss'))")
    [void]$lines.Add("files=$($selected.Count)")
    foreach ($item in $selected) {
        [void]$lines.Add(("{0}`t{1}" -f $item.Relative, $item.File.Length))
        $entry = $zip.CreateEntry($item.Relative, [System.IO.Compression.CompressionLevel]::Optimal)
        $entry.LastWriteTime = $item.File.LastWriteTime
        $input = [IO.File]::OpenRead($item.File.FullName)
        try {
            $output = $entry.Open()
            try {
                $input.CopyTo($output)
            } finally {
                $output.Dispose()
            }
        } finally {
            $input.Dispose()
        }
    }
    $manifest = $zip.CreateEntry('_manifest.txt', [System.IO.Compression.CompressionLevel]::NoCompression)
    $writer = [System.IO.StreamWriter]::new($manifest.Open())
    try {
        foreach ($line in $lines) {
            $writer.WriteLine($line)
        }
    } finally {
        $writer.Dispose()
    }
} finally {
    $zip.Dispose()
    $stream.Dispose()
}

"Файлов конфигурации: $($selected.Count)"
"Готово: $outputFull"

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

CLI 1.0.0

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

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

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

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

Категория

Архивы

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