如何通过脚本压缩指定日期范围的文件?现有批处理脚本报错求助
如何通过脚本压缩指定日期范围的文件?现有批处理脚本报错求助
兄弟,我来帮你搞定这个问题!先说说你遇到的报错根源,再给你优化整个脚本的可靠性~
你的报错原因
你当前的错误'zdiryearyear" -mx5' is not recognized as an internal or external command,核心问题是7-Zip的路径包含空格,但调用时没加引号。你的脚本里set 7z=C:\Program Files\7-Zip\7z.exe,直接用%7z%调用时,系统会把C:\Program当成命令,剩下的部分乱成一团,才出现了奇怪的错误提示。
修复后的批处理脚本
我给你调整了脚本,不仅解决了报错,还优化了文件筛选的可靠性(原脚本用dir + find依赖系统日期格式,容易误判):
@echo off setlocal enabledelayedexpansion :: 设置7z路径,带引号避免空格问题 set "7z=C:\Program Files\7-Zip\7z.exe" if not exist "%7z%" ( set /p "7z=Path to 7-zip executable? " :: 确保用户输入的路径格式正确 if not "!7z:~0,1!"=="\"" set "7z=!7z!" if not "!7z:~-1!"=="\"" set "7z=!7z!" ) set /p "year=What year do you wish to archive? " set /p "dir=What is the path of the files you wish to archive? " :: 处理目标路径末尾的反斜杠,避免拼接出错 if not "!dir:~-1!"=="\" set "dir=!dir!\" mkdir "!year!" 2>nul :: 用forfiles精准筛选指定年份修改的文件,不受系统区域设置影响 forfiles /p "!dir!" /m *.* /d +01/01/!year! /d -12/31/!year! /c "cmd /c move @path \"!year!\"" :: 调用7z时给所有带空格的变量加引号 "%7z%" a -tzip "!dir!!year!.zip" "!year!" -mx5 set /p "confirm=I'm about to delete the !year! folder. Hit Ctrl-C to cancel, or Enter to continue." rmdir /q /s "!year!" echo Done. endlocal
关键改进点
- 给
%7z%的调用加上引号,彻底解决空格路径导致的命令解析错误; - 启用
delayedexpansion处理变量动态展开,避免特殊字符干扰; - 用
forfiles替代dir + find,直接按日期范围筛选文件,不会误匹配文件名里的年份字符串,也不受系统日期格式影响; - 自动处理路径末尾的反斜杠,避免路径拼接出错。
更可靠的PowerShell替代方案
批处理处理日期始终有点麻烦,如果你愿意用PowerShell,脚本会更简洁精准:
$7zPath = "C:\Program Files\7-Zip\7z.exe" if (-not (Test-Path $7zPath)) { $7zPath = Read-Host "Path to 7-zip executable" } $year = Read-Host "What year do you wish to archive?" $targetDir = Read-Host "What is the path of the files you wish to archive?" $yearFolder = Join-Path $PWD.Path $year New-Item -ItemType Directory -Path $yearFolder -Force | Out-Null # 精准筛选指定年份修改的文件 $startDate = Get-Date -Year $year -Month 1 -Day 1 $endDate = Get-Date -Year $year -Month 12 -Day 31 -Hour 23 -Minute 59 -Second 59 Get-ChildItem -Path $targetDir -File | Where-Object { $_.LastWriteTime -ge $startDate -and $_.LastWriteTime -le $endDate } | Move-Item -Destination $yearFolder # 执行压缩 & $7zPath a -tzip (Join-Path $targetDir "$year.zip") $yearFolder -mx5 # 确认删除临时文件夹 $confirm = Read-Host "I'm about to delete the $year folder. Hit Ctrl-C to cancel, or Enter to continue" Remove-Item -Path $yearFolder -Recurse -Force Write-Host "Done."
这个脚本直接通过文件的LastWriteTime属性筛选,完全不受系统设置影响,逻辑也更清晰。
备注:内容来源于stack exchange,提问作者Pribovich
相关产品推荐
相关产品推荐

