batch-file - 7zip 批处理脚本在带有感叹号的文件夹上中断
问题描述
我正在使用批处理脚本将数千个文件夹压缩到各自的存档中。我注意到15 号之后包含感叹号 (!)的每个文件夹都会破坏脚本并出现以下错误:
Scan WARNINGS for files and folders:
The system cannot find the file specified.
有问题的脚本:
@Echo OFF
SetLocal EnableDelayedExpansion
Rem // 7-Zip Executable Path
Set sevenZip="C:\Program Files\7-Zip\7z.exe"
Rem // START: NewLine Variable Hack
Set newLine=^
Rem // END: NewLine Variable Hack !! DO NOT DELETE 2 EMPTY LINES ABOVE !!
Rem // Set ErrorLog Variables
Set errorCount=0
Set separator=--------------------------------------------------------
Set errorLog=!newLine!!newLine!!separator!!newLine!!newLine!
Set errorPrefix=ERROR @:
Set successMessage=All Files Were Successfully Archived
Rem // Loop Through Each Argument
SetLocal DisableDelayedExpansion
for %%x in (%*) do (
Rem // Use Current Argument To set File, Folder, & Archive Paths
SetLocal DisableDelayedExpansion
Set filePath="%%~x"
Set directoryFiles="%%~x\*"
Set archivePath="%%~x.7z"
SetLocal EnableDelayedExpansion
Rem // Source Is A Folder
if exist !directoryFiles! (
Set sourcePath=!directoryFiles!
)
Rem // Source Is A File
if not exist !directoryFiles! (
Set sourcePath=!filePath!
)
Rem // Print Separator To Divide 7-Zip Output
echo !newLine!!newLine!!separator!!newLine!!newLine!
Rem // Add Files To Zip Archive
!sevenZip! A -T7Z !archivePath! !sourcePath!
Rem // Log Errors
if ErrorLevel 1 (
Set /A errorCount=errorCount+1
Set errorLog=!errorLog!!newLine!!errorPrefix!!sourcePath!
)
)
Rem // Print ErrorLog
if !errorCount!==0 (
Set errorLog=!errorLog!!newLine!!successMessage!
)
Echo !errorLog!!newLine!!newLine!!newLine!
Rem // Keep Window Open To View ErrorLog
pause
我究竟做错了什么?使用 7-Zip 版本 19.00 和 21.01 alpha 进行测试。
解决方案
您的问题是 setlocal/endlocal 不平衡。
在您的循环中,您打开两个 setlocal,但不使用 endlocal关闭它们。
但是 setlocal 限制为 32 个级别,然后它会失败。
endlocal
您应该在循环右括号之前简单地添加两个。
推荐阅读
- node.js - 数据无法在 mongodb 中更新
- php - 通过匹配文本获取环境变量名称
- php - 安全性不支持 PHP 5.6,那么为什么还没有弃用 PHP 5.6?
- angular - Angular 5 服务读取本地 .json 文件错误:未知编译器选项“resolveJsonModule”和“esModuleInterop”
- c# - 在方法中创建或更改对象时的约定
- android - 录制时是否可以获取视频的缩略图
- terraform - 尝试多次循环小部件字段时,Terraform 代码中出现 400 错误
- reactjs - 具有替代数组键格式的 Primereact Dropdown
- excel - 从另一个工作簿复制数据,取消隐藏列并首先关闭自动过滤器,粘贴到当前工作簿并关闭工作簿
- python - 为什么这些场景中的结果不同?