批量给文件添加校验和脚本

wen 实用脚本 1

本文目录导读:

批量给文件添加校验和脚本

  1. Bash 版本(Linux/macOS)
  2. PowerShell 版本(Windows)
  3. 使用说明
  4. 功能特点
  5. 输出格式

Bash 版本(Linux/macOS)

#!/bin/bash
# 批量给文件添加校验和脚本
# 用法: ./add_checksum.sh [目录路径] [校验和类型]
# 默认配置
TARGET_DIR="${1:-.}"  # 默认当前目录
CHECKSUM_TYPE="${2:-sha256}"  # 默认使用 SHA256
# 支持的校验和类型
SUPPORTED_TYPES=("md5" "sha1" "sha256" "sha512" "sha224" "sha384")
# 检查校验和类型是否支持
validate_type() {
    local type=$1
    for supported_type in "${SUPPORTED_TYPES[@]}"; do
        if [[ "$type" == "$supported_type" ]]; then
            return 0
        fi
    done
    echo "错误: 不支持的校验和类型 '$type'"
    echo "支持的类型: ${SUPPORTED_TYPES[*]}"
    exit 1
}
# 获取校验和命令
get_checksum_cmd() {
    local type=$1
    case "$type" in
        md5)    echo "md5sum" ;;
        sha1)   echo "sha1sum" ;;
        sha256) echo "sha256sum" ;;
        sha512) echo "sha512sum" ;;
        sha224) echo "sha224sum" ;;
        sha384) echo "sha384sum" ;;
    esac
}
# 主函数
main() {
    # 验证参数
    validate_type "$CHECKSUM_TYPE"
    # 检查目标目录
    if [[ ! -d "$TARGET_DIR" ]]; then
        echo "错误: 目录 '$TARGET_DIR' 不存在"
        exit 1
    fi
    # 获取校验和命令
    CHECKSUM_CMD=$(get_checksum_cmd "$CHECKSUM_TYPE")
    # 检查命令是否存在
    if ! command -v "$CHECKSUM_CMD" &> /dev/null; then
        echo "错误: 命令 '$CHECKSUM_CMD' 未安装"
        exit 1
    fi
    echo "开始对目录 '$TARGET_DIR' 中的文件添加 $CHECKSUM_TYPE 校验和..."
    # 计数器
    processed=0
    skipped=0
    errors=0
    # 遍历所有文件(排除目录和校验和文件本身)
    while IFS= read -r -d '' file; do
        # 跳过校验和文件本身
        if [[ "$file" == *".$CHECKSUM_TYPE" ]]; then
            continue
        fi
        # 计算校验和
        if checksum=$("$CHECKSUM_CMD" "$file" | cut -d' ' -f1); then
            # 创建校验和文件
            checksum_file="${file}.${CHECKSUM_TYPE}"
            # 检查是否已存在校验和文件
            if [[ -f "$checksum_file" ]]; then
                echo "跳过: $file (校验和文件已存在)"
                ((skipped++))
                continue
            fi
            # 写入校验和
            echo "$checksum  $file" > "$checksum_file"
            echo "处理: $file -> $checksum_file"
            ((processed++))
        else
            echo "错误: 无法计算 '$file' 的校验和"
            ((errors++))
        fi
    done < <(find "$TARGET_DIR" -type f -print0)
    # 显示统计信息
    echo ""
    echo "完成! 统计:"
    echo "  处理成功: $processed"
    echo "  跳过: $skipped"
    echo "  错误: $errors"
}
# 运行主函数
main

PowerShell 版本(Windows)

<#
.SYNOPSIS
    批量给文件添加校验和脚本
.DESCRIPTION
    遍历指定目录中的所有文件,为每个文件生成校验和文件
.PARAMETER TargetPath
    目标目录路径,默认为当前目录
.PARAMETER ChecksumType
    校验和类型,可选 MD5, SHA1, SHA256, SHA384, SHA512,默认为 SHA256
.PARAMETER Force
    强制覆盖已存在的校验和文件
.EXAMPLE
    .\Add-FileChecksum.ps1
    .\Add-FileChecksum.ps1 -TargetPath "C:\MyFiles" -ChecksumType MD5
    .\Add-FileChecksum.ps1 -TargetPath ".\downloads" -ChecksumType SHA256 -Force
#>
param(
    [Parameter(Position=0)]
    [string]$TargetPath = ".",
    [Parameter(Position=1)]
    [ValidateSet("MD5", "SHA1", "SHA256", "SHA384", "SHA512")]
    [string]$ChecksumType = "SHA256",
    [switch]$Force
)
function Get-FileChecksum {
    param(
        [string]$FilePath,
        [string]$Algorithm
    )
    try {
        $hash = Get-FileHash -Path $FilePath -Algorithm $Algorithm
        return $hash.Hash.ToLower()
    }
    catch {
        Write-Error "无法计算 '$FilePath' 的校验和: $_"
        return $null
    }
}
function Main {
    # 解析目标路径
    $resolvedPath = Resolve-Path $TargetPath -ErrorAction SilentlyContinue
    if (-not $resolvedPath) {
        Write-Error "目录 '$TargetPath' 不存在"
        return
    }
    Write-Host "开始对目录 '$resolvedPath' 中的文件添加 $ChecksumType 校验和..." -ForegroundColor Green
    # 计数器
    $processed = 0
    $skipped = 0
    $errors = 0
    # 获取所有文件
    $files = Get-ChildItem -Path $resolvedPath -File -Recurse
    foreach ($file in $files) {
        # 跳过校验和文件本身
        if ($file.Extension -eq ".$ChecksumType") {
            continue
        }
        $checksumFilePath = "$($file.FullName).$ChecksumType"
        # 检查校验和文件是否已存在
        if ((Test-Path $checksumFilePath) -and (-not $Force)) {
            Write-Host "跳过: $($file.Name) (校验和文件已存在)" -ForegroundColor Yellow
            $skipped++
            continue
        }
        # 计算校验和
        $checksum = Get-FileChecksum -FilePath $file.FullName -Algorithm $ChecksumType
        if ($checksum) {
            # 写入校验和文件
            $content = "$checksum  $($file.Name)`r`n"
            try {
                Set-Content -Path $checksumFilePath -Value $content -NoNewline
                Write-Host "处理: $($file.Name) -> $($file.Name).$ChecksumType" -ForegroundColor Green
                $processed++
            }
            catch {
                Write-Error "写入校验和文件失败: $_"
                $errors++
            }
        }
        else {
            $errors++
        }
    }
    # 显示统计信息
    Write-Host "`n完成! 统计:" -ForegroundColor Cyan
    Write-Host "  处理成功: $processed" -ForegroundColor Green
    Write-Host "  跳过: $skipped" -ForegroundColor Yellow
    Write-Host "  错误: $errors" -ForegroundColor Red
}
# 运行主函数
Main

使用说明

Bash 版本

# 添加执行权限
chmod +x add_checksum.sh
# 基本用法(当前目录,使用SHA256)
./add_checksum.sh
# 指定目录和校验和类型
./add_checksum.sh /path/to/files md5
./add_checksum.sh /path/to/files sha256
./add_checksum.sh /path/to/files sha512

PowerShell 版本

# 设置执行策略(如果需要)
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
# 基本用法
.\Add-FileChecksum.ps1
# 指定目录和校验和类型
.\Add-FileChecksum.ps1 -TargetPath "C:\MyFiles" -ChecksumType MD5
# 强制覆盖已存在的校验和文件
.\Add-FileChecksum.ps1 -TargetPath ".\downloads" -ChecksumType SHA256 -Force

功能特点

  1. 支持多种校验和类型:MD5、SHA1、SHA256、SHA384、SHA512
  2. 递归处理:自动遍历子目录
  3. 跳过已存在的校验和文件:避免重复处理
  4. 详细的错误处理:捕获并报告错误
  5. 统计信息:显示处理、跳过和错误的数量
  6. 跨平台:提供 Windows 和 Linux/macOS 版本

输出格式

校验和文件的内容格式:

<校验和值>  文件名

SHA256):

e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855  myfile.txt

这些脚本会自动创建与文件名相同的校验和文件(file.txt.sha256),并包含计算出的校验和值。

抱歉,评论功能暂时关闭!