本文目录导读:

方案1:使用 WinRAR 添加恢复记录(适用于 .rar 文件)
Windows Batch 脚本 (add_recovery.bat)
@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion
echo 批量添加恢复记录脚本
echo ========================
:: 设置 WinRAR 路径(根据实际安装位置修改)
set WINRAR_PATH="C:\Program Files\WinRAR\WinRAR.exe"
:: 检查 WinRAR 是否可用
if not exist %WINRAR_PATH% (
echo 错误:未找到 WinRAR,请检查路径
pause
exit /b 1
)
:: 检查参数
if "%1"=="" (
echo 用法:%0 ^<文件类型^> [恢复记录百分比]
echo 示例:%0 *.rar 5
echo 示例:%0 *.zip 3
pause
exit /b 1
)
set FILE_PATTERN=%1
set RECOVERY_PERCENT=%2
if "%RECOVERY_PERCENT%"=="" set RECOVERY_PERCENT=5
echo 文件类型:%FILE_PATTERN%
echo 恢复记录:%RECOVERY_PERCENT%%%
echo.
echo 正在处理文件...
:: 遍历匹配的文件
for %%f in (%FILE_PATTERN%) do (
echo 处理:%%f
%WINRAR_PATH% c -rr%RECOVERY_PERCENT% "%%f"
if !errorlevel! equ 0 (
echo ✓ 成功添加恢复记录
) else (
echo ✗ 添加恢复记录失败
)
echo.
)
echo 处理完成!
pause
方案2:使用 7-Zip 创建带恢复记录的压缩包
PowerShell 脚本 (Add-RecoveryRecord.ps1)
# 批量创建带恢复记录的压缩文件
param(
[Parameter(Mandatory=$true)]
[string]$SourcePath,
[Parameter(Mandatory=$true)]
[string]$FilePattern = "*.zip",
[int]$RecoveryPercent = 5,
[string]$OutputDir = ""
)
# 7-Zip 路径(根据安装位置修改)
$7zipPath = "C:\Program Files\7-Zip\7z.exe"
if (-not (Test-Path $7zipPath)) {
Write-Error "未找到 7-Zip,请检查安装路径"
exit 1
}
# 获取源文件
$files = Get-ChildItem -Path $SourcePath -Filter $FilePattern
if ($files.Count -eq 0) {
Write-Warning "未找到匹配的文件"
exit 0
}
# 创建输出目录
if ([string]::IsNullOrEmpty($OutputDir)) {
$OutputDir = Join-Path $SourcePath "WithRecovery"
}
New-Item -ItemType Directory -Force -Path $OutputDir | Out-Null
Write-Host "开始处理 $($files.Count) 个文件..."
Write-Host "恢复记录大小:$RecoveryPercent%"
foreach ($file in $files) {
$outputFile = Join-Path $OutputDir $file.Name
$newName = [System.IO.Path]::GetFileNameWithoutExtension($file.Name) + "_recovery.7z"
$outputPath = Join-Path $OutputDir $newName
Write-Host "处理: $($file.Name)"
# 7-Zip 带恢复记录压缩(7z格式支持)
$arguments = @(
"a",
"-t7z",
"-mx=5", # 压缩等级
"-mhe=off", # 不加密头
"-mqs=on", # 按文件排序
"-mmt=on", # 多线程
"-ms=on", # 固实压缩
"-mtr=$RecoveryPercent", # 恢复记录百分比
"`"$outputPath`"",
"`"$($file.FullName)`""
)
$process = Start-Process -FilePath $7zipPath -ArgumentList $arguments -Wait -NoNewWindow -PassThru
if ($process.ExitCode -eq 0) {
Write-Host " ✓ 创建成功: $newName" -ForegroundColor Green
} else {
Write-Host " ✗ 创建失败" -ForegroundColor Red
}
}
Write-Host ""
Write-Host "处理完成!所有文件已保存在: $OutputDir"
方案3:Python 通用脚本 (add_recovery.py)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import glob
import subprocess
import argparse
from pathlib import Path
def add_recovery_winrar(file_path, recovery_percent=5):
"""使用 WinRAR 添加恢复记录"""
winrar_paths = [
r"C:\Program Files\WinRAR\WinRAR.exe",
r"C:\Program Files (x86)\WinRAR\WinRAR.exe",
]
winrar = None
for path in winrar_paths:
if os.path.exists(path):
winrar = path
break
if not winrar:
raise FileNotFoundError("未找到 WinRAR")
cmd = [
winrar, "c", f"-rr{recovery_percent}",
f'"{file_path}"'
]
result = subprocess.run(
" ".join(cmd),
shell=True,
capture_output=True,
text=True
)
return result.returncode == 0
def add_recovery_7zip(file_path, recovery_percent=5):
"""使用 7-Zip 创建带恢复记录的新文件"""
seven_zip_paths = [
r"C:\Program Files\7-Zip\7z.exe",
r"C:\Program Files (x86)\7-Zip\7z.exe",
]
seven_zip = None
for path in seven_zip_paths:
if os.path.exists(path):
seven_zip = path
break
if not seven_zip:
raise FileNotFoundError("未找到 7-Zip")
# 创建带恢复记录的新 7z 文件
output_file = Path(file_path).stem + "_recovery.7z"
cmd = [
seven_zip, "a",
"-t7z",
"-mx=5",
"-mhe=off",
"-mqs=on",
"-mmt=on",
"-ms=on",
f"-mtr={recovery_percent}",
f'"{output_file}"',
f'"{file_path}"'
]
result = subprocess.run(
" ".join(cmd),
shell=True,
capture_output=True,
text=True
)
return result.returncode == 0, output_file
def main():
parser = argparse.ArgumentParser(description="批量给文件添加恢复记录")
parser.add_argument("pattern", help="文件匹配模式,*.rar")
parser.add_argument("-p", "--percent", type=int, default=5,
help="恢复记录百分比(默认:5)")
parser.add_argument("-t", "--tool", choices=["winrar", "7zip"], default="winrar",
help="使用的工具(默认:winrar)")
parser.add_argument("-d", "--directory", default=".",
help="文件目录(默认:当前目录)")
args = parser.parse_args()
# 获取匹配的文件
search_pattern = os.path.join(args.directory, args.pattern)
files = glob.glob(search_pattern)
if not files:
print(f"未找到匹配的文件: {args.pattern}")
return
print(f"找到 {len(files)} 个文件")
print(f"恢复记录百分比: {args.percent}%")
print(f"使用工具: {args.tool}")
print("-" * 50)
success = 0
failed = 0
for file_path in files:
print(f"处理: {os.path.basename(file_path)}")
try:
if args.tool == "winrar":
if add_recovery_winrar(file_path, args.percent):
print(" ✓ 添加成功")
success += 1
else:
print(" ✗ 添加失败")
failed += 1
else: # 7zip
result, output_file = add_recovery_7zip(file_path, args.percent)
if result:
print(f" ✓ 创建新文件: {output_file}")
success += 1
else:
print(" ✗ 创建失败")
failed += 1
except Exception as e:
print(f" ✗ 错误: {e}")
failed += 1
print("-" * 50)
print(f"处理完成!成功: {success}, 失败: {failed}")
if __name__ == "__main__":
main()
使用说明
Windows Batch 脚本
- 确保已安装 WinRAR
- 修改脚本中的 WinRAR 路径(如果需要)
- 运行:
add_recovery.bat *.rar 5
PowerShell 脚本
- 确保已安装 7-Zip
- 修改脚本中的 7-Zip 路径
- 运行:
.\Add-RecoveryRecord.ps1 -SourcePath "C:\Backup" -FilePattern "*.zip" -RecoveryPercent 5
Python 脚本
-
安装 Python(3.6+)
-
确保有 WinRAR 或 7-Zip
-
运行:
# 使用 WinRAR python add_recovery.py "*.rar" -p 5 -t winrar # 使用 7-Zip python add_recovery.py "*.zip" -p 5 -t 7zip
注意事项
- 备份文件:操作前建议先备份重要文件
- 恢复记录大小:建议 3%-10%,太大影响空间,太小效果不佳
- 文件格式:
- WinRAR:支持修改现有 .rar 文件
- 7-Zip:需要创建新文件(原文件不变)
- 权限问题:确保脚本有文件读写权限
- 大文件处理:处理大文件时需要耐心等待
选择适合你环境的脚本使用!