↓ 跳过正文

压缩归档文件夹脚本

·1749 字· loading · loading · · ·
lightmon
作者
lightmon
该博主太懒了,尚未添加简介。
目录

PowerShell
#

[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
param(
    [Parameter(Position = 0)]
    [ValidateNotNullOrEmpty()]
    [string]$TargetPath = $PSScriptRoot,

    [string]$SevenZipPath,

    [switch]$OverwriteExisting
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

function Get-SevenZipExecutable {
    param([string]$RequestedPath)

    if ($RequestedPath) {
        $item = Get-Item -LiteralPath $RequestedPath -ErrorAction Stop
        if ($item.PSIsContainer) {
            throw "SevenZipPath is a directory, not an executable: $RequestedPath"
        }
        return $item.FullName
    }

    foreach ($name in @('7z.exe', '7zz.exe', '7za.exe')) {
        $command = Get-Command $name -CommandType Application -ErrorAction SilentlyContinue |
            Select-Object -First 1
        if ($null -ne $command) {
            return $command.Source
        }
    }

    foreach ($candidate in @(
        (Join-Path $env:ProgramFiles '7-Zip\7z.exe'),
        (Join-Path ${env:ProgramFiles(x86)} '7-Zip\7z.exe')
    )) {
        if ($candidate -and (Test-Path -LiteralPath $candidate -PathType Leaf)) {
            return $candidate
        }
    }

    throw '7-Zip was not found. Install it or pass -SevenZipPath C:\path\to\7z.exe.'
}

$target = Get-Item -LiteralPath $TargetPath -Force -ErrorAction Stop
if (-not $target.PSIsContainer) {
    throw "TargetPath is not a directory: $TargetPath"
}

$sevenZip = Get-SevenZipExecutable -RequestedPath $SevenZipPath
$folders = @(Get-ChildItem -LiteralPath $target.FullName -Directory -Force | Sort-Object Name)

if ($folders.Count -eq 0) {
    Write-Host "No subfolders found in: $($target.FullName)"
    return
}

Write-Host "Target : $($target.FullName)"
Write-Host "7-Zip : $sevenZip"
Write-Host "Folders: $($folders.Count)"

$failures = [System.Collections.Generic.List[string]]::new()
$completedCount = 0
$skippedCount = 0

foreach ($folder in $folders) {
    $zipPath = Join-Path $target.FullName ($folder.Name + '.zip')
    $temporaryZipPath = Join-Path $target.FullName (
        '{0}.partial-{1}.zip' -f $folder.Name, [guid]::NewGuid().ToString('N')
    )

    if (($folder.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
        Write-Warning "Skipping link/junction directory: $($folder.FullName)"
        $skippedCount++
        continue
    }

    if ((Test-Path -LiteralPath $zipPath) -and -not $OverwriteExisting) {
        Write-Warning "Skipping because archive already exists: $zipPath (use -OverwriteExisting to replace it)"
        $skippedCount++
        continue
    }

    $action = "create and verify '$zipPath', then delete the source directory"
    if (-not $PSCmdlet.ShouldProcess($folder.FullName, $action)) {
        $skippedCount++
        continue
    }

    Write-Host "`n[ARCHIVE] $($folder.Name)"

    try {
        Push-Location -LiteralPath $target.FullName
        try {
            & $sevenZip a -tzip -mx=5 -y -- $temporaryZipPath ('.\' + $folder.Name)
            if ($LASTEXITCODE -ne 0) {
                throw "7-Zip archive command returned exit code $LASTEXITCODE."
            }
        }
        finally {
            Pop-Location
        }

        & $sevenZip t -tzip -- $temporaryZipPath
        if ($LASTEXITCODE -ne 0) {
            throw "7-Zip validation returned exit code $LASTEXITCODE."
        }

        Move-Item -LiteralPath $temporaryZipPath -Destination $zipPath -Force:$OverwriteExisting.IsPresent
        Remove-Item -LiteralPath $folder.FullName -Recurse -Force
        $completedCount++
        Write-Host "[DONE] $($folder.Name) -> $zipPath; source directory removed."
    }
    catch {
        if (Test-Path -LiteralPath $temporaryZipPath) {
            Remove-Item -LiteralPath $temporaryZipPath -Force -ErrorAction SilentlyContinue
        }
        Write-Warning "Failed for '$($folder.FullName)'. The source directory was kept. $($_.Exception.Message)"
        $failures.Add($folder.FullName)
    }
}

if ($WhatIfPreference) {
    Write-Host "`nPreview completed: no folders were changed."
    return
}

Write-Host ("`nCompleted: {0} folder(s) archived, verified, and removed." -f $completedCount)

if ($skippedCount -gt 0) {
    Write-Warning ("{0} folder(s) were skipped and not removed." -f $skippedCount)
}

if ($failures.Count -gt 0) {
    Write-Warning ("{0} folder(s) failed and were not removed." -f $failures.Count)
}

Bash Shell
#

#!/usr/bin/env bash

set -Eeuo pipefail

# =========================
# 参数默认值
# =========================

TARGET_PATH="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
SEVEN_ZIP_PATH=""
OVERWRITE_EXISTING=false
DRY_RUN=false

# =========================
# 显示帮助
# =========================

usage() {
    cat <<EOF
用法:
  $(basename "$0") [选项] [TARGET_PATH]

选项:
  -7, --7zip PATH       指定 7z 可执行文件
  -o, --overwrite       覆盖已经存在的 ZIP
  -n, --dry-run         只预览,不实际修改文件
  -h, --help            显示帮助

示例:
  $(basename "$0")
  $(basename "$0") /data/photos
  $(basename "$0") -o /data/photos
  $(basename "$0") --7zip /usr/bin/7z /data/photos
  $(basename "$0") --dry-run /data/photos
EOF
}

# =========================
# 查找 7-Zip
# =========================

get_seven_zip_executable() {
    local requested_path="${1:-}"

    # 用户明确指定路径
    if [[ -n "$requested_path" ]]; then
        if [[ ! -f "$requested_path" ]]; then
            echo "错误:SevenZipPath 不是文件:$requested_path" >&2
            return 1
        fi

        if [[ ! -x "$requested_path" ]]; then
            echo "错误:7-Zip 文件不可执行:$requested_path" >&2
            return 1
        fi

        printf '%s\n' "$requested_path"
        return 0
    fi

    # 先从 PATH 中查找
    local name
    for name in 7z 7zz 7za; do
        if command -v "$name" >/dev/null 2>&1; then
            command -v "$name"
            return 0
        fi
    done

    echo "错误:没有找到 7-Zip。" >&2
    echo "请安装 7-Zip,或者使用 --7zip 指定路径。" >&2
    return 1
}

# =========================
# 删除临时 ZIP
# =========================

cleanup_temp() {
    if [[ -n "${TEMPORARY_ZIP_PATH:-}" && -e "$TEMPORARY_ZIP_PATH" ]]; then
        rm -f -- "$TEMPORARY_ZIP_PATH" || true
    fi
}

# =========================
# 解析参数
# =========================

POSITIONAL_ARGS=()

while [[ $# -gt 0 ]]; do
    case "$1" in
        -7|--7zip)
            if [[ $# -lt 2 ]]; then
                echo "错误:$1 需要一个路径参数。" >&2
                exit 2
            fi
            SEVEN_ZIP_PATH="$2"
            shift 2
            ;;

        -o|--overwrite)
            OVERWRITE_EXISTING=true
            shift
            ;;

        -n|--dry-run)
            DRY_RUN=true
            shift
            ;;

        -h|--help)
            usage
            exit 0
            ;;

        --)
            shift
            while [[ $# -gt 0 ]]; do
                POSITIONAL_ARGS+=("$1")
                shift
            done
            ;;

        -*)
            echo "错误:未知参数:$1" >&2
            usage >&2
            exit 2
            ;;

        *)
            POSITIONAL_ARGS+=("$1")
            shift
            ;;
    esac
done

# 最多允许一个位置参数
if [[ "${#POSITIONAL_ARGS[@]}" -gt 1 ]]; then
    echo "错误:只能指定一个 TARGET_PATH。" >&2
    exit 2
fi

if [[ "${#POSITIONAL_ARGS[@]}" -eq 1 ]]; then
    TARGET_PATH="${POSITIONAL_ARGS[0]}"
fi

# =========================
# 检查目标目录
# =========================

if [[ ! -d "$TARGET_PATH" ]]; then
    echo "错误:TargetPath 不是目录:$TARGET_PATH" >&2
    exit 1
fi

TARGET_PATH="$(cd -- "$TARGET_PATH" && pwd)"

# =========================
# 查找 7-Zip
# =========================

SEVEN_ZIP="$(get_seven_zip_executable "$SEVEN_ZIP_PATH")"

# =========================
# 收集子目录
# =========================

folders=()

while IFS= read -r -d '' folder; do
    folders+=("$folder")
done < <(
    find "$TARGET_PATH" \
        -mindepth 1 \
        -maxdepth 1 \
        -type d \
        -print0 |
    sort -z
)

if [[ "${#folders[@]}" -eq 0 ]]; then
    echo "目标目录中没有找到子目录:$TARGET_PATH"
    exit 0
fi

echo "Target : $TARGET_PATH"
echo "7-Zip  : $SEVEN_ZIP"
echo "Folders: ${#folders[@]}"

if [[ "$DRY_RUN" == true ]]; then
    echo "Mode   : DRY-RUN"
fi

# =========================
# 统计
# =========================

failures=()
completed_count=0
skipped_count=0

# =========================
# 处理每个目录
# =========================

for folder in "${folders[@]}"; do

    folder_name="$(basename -- "$folder")"
    zip_path="$TARGET_PATH/$folder_name.zip"

    temporary_zip_path="$TARGET_PATH/${folder_name}.partial-$(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid).zip"

    # ---------------------------------
    # 跳过符号链接 / junction
    # ---------------------------------

    if [[ -L "$folder" ]]; then
        echo "警告:跳过符号链接目录:$folder" >&2
        ((skipped_count+=1))
        continue
    fi

    # ---------------------------------
    # ZIP 已经存在,而且没有要求覆盖
    # ---------------------------------

    if [[ -e "$zip_path" && "$OVERWRITE_EXISTING" != true ]]; then
        echo "警告:ZIP 已经存在,跳过:$zip_path" >&2
        echo "       如果希望覆盖,请使用 --overwrite" >&2
        ((skipped_count+=1))
        continue
    fi

    # ---------------------------------
    # Dry Run
    # ---------------------------------

    if [[ "$DRY_RUN" == true ]]; then
        echo
        echo "[WOULD ARCHIVE] $folder_name"
        echo "  Source : $folder"
        echo "  ZIP    : $zip_path"
        echo "  Action : create + verify + delete source"
        ((skipped_count+=1))
        continue
    fi

    echo
    echo "[ARCHIVE] $folder_name"

    # ---------------------------------
    # 确保失败时删除临时 ZIP
    # ---------------------------------

    TEMPORARY_ZIP_PATH="$temporary_zip_path"
    trap cleanup_temp RETURN

    if (
        cd -- "$TARGET_PATH"

        echo "  -> Creating archive..."

        "$SEVEN_ZIP" a \
            -tzip \
            -mx=5 \
            -y \
            -- \
            "$temporary_zip_path" \
            "./$folder_name"

        echo "  -> Verifying archive..."

        "$SEVEN_ZIP" t \
            -tzip \
            -- \
            "$temporary_zip_path"

        echo "  -> Archive verified."

        echo "  -> Moving archive into place..."

        if [[ "$OVERWRITE_EXISTING" == true ]]; then
            mv -f -- "$temporary_zip_path" "$zip_path"
        else
            mv -- "$temporary_zip_path" "$zip_path"
        fi

        echo "  -> Removing source directory..."

        rm -rf -- "$folder"

    ); then

        ((completed_count+=1))

        echo "[DONE] $folder_name -> $zip_path"
        echo "       source directory removed."

    else

        echo "警告:处理失败:$folder" >&2
        echo "       源目录已保留。" >&2

        failures+=("$folder")

    fi

    TEMPORARY_ZIP_PATH=""

done

# =========================
# 最终统计
# =========================

if [[ "$DRY_RUN" == true ]]; then
    echo
    echo "Preview completed: 没有修改任何目录。"
    exit 0
fi

echo
echo "Completed: $completed_count 个目录已压缩、验证并删除。"

if [[ "$skipped_count" -gt 0 ]]; then
    echo "警告:$skipped_count 个目录被跳过,没有删除。" >&2
fi

if [[ "${#failures[@]}" -gt 0 ]]; then
    echo "警告:${#failures[@]} 个目录处理失败,没有删除:" >&2

    for failed in "${failures[@]}"; do
        echo "  - $failed" >&2
    done
fi

# 如果有失败,可以用非零退出码告诉调用者
if [[ "${#failures[@]}" -gt 0 ]]; then
    exit 1
fi

exit 0
Footer Background

© 2026 lightmon

由 Hugo & Blowfish 强力驱动