【发布时间】:2018-05-10 21:38:12
【问题描述】:
我正在编写一个批处理文件,它将在目录中搜索大于 25Kb 的 .jpg 文件,然后运行命令来压缩这些文件。
目前,当我对整个目录运行该命令时,该命令将压缩每个 .jpg 文件,但我正在努力让该命令仅对所述目录中大于 25Kb 的文件运行。代码如下:
@echo off
SETLOCAL EnableDelayedExpansion
SET maxbytesize=25000
SET logfile=A:\JobLogs\PhotoCompression.log
ECHO Starting compression job at %date% %time% >> %logfile%
:: Runs the following if/else statement against all files in the directory
FOR %%G IN (C:\My\Directory) DO (
:: If file size is greater than or equal to 25Kb, run the ImageMagick command and append the name of the processed file to logfile
IF [ %var% GTR %maxbytesize% ]
magick mogrify -resize "140>^" -quality 75% -depth 8 -units PixelsPerInch -density 72x72 -strip *.jpg
ECHO %%G has been compressed %date% %time% >> %logfile%
:: No files are larger than 25Kb, write "All files are compressed" to logfile
ELSE ECHO All files are compressed %date% %time% >> %logfile%
)
:: Appends completed job status to logfile
ECHO Job is complete %date% %time% >> %logfile%
Exit
命令 "magick mogrify -resize "140>^" -quality 75% -depth 8 -units PixelsPerInch -density 72x72 -strip *.jpg" 是一个 ImageMagick 命令,可以忽略,因为它在运行时会成功压缩照片如上所述,针对整个目录。
请注意,我在 if 条件下尝试了 %G、%%G、%G% 和 %var% 的变体,但没有成功。
【问题讨论】:
-
你可以完全避免延迟扩展的麻烦,不做多行命令块。只需调用带有相关参数的子程序并处理它们。并且停止使用
::代替 REM,这是一种未记录的 hack,它利用了 cmd.exe 中的一个错误,实际上可能有一天会得到修复。 -
var未在您的脚本中定义。要么这是一个错误,要么你没有发布 MCVE。拿tour、阅读How to Ask和minimal reproducible example。 -
IF 命令的帮助文件中的哪个位置说要使用括号进行比较?它也没有显示使用 IF....ELSE 的示例,就像您尝试使用它一样。
-
-resize "140>^"看起来不对!width:给定宽度,自动选择高度以保持纵横比。widthxheight^:给定宽度和高度的最小值,保留纵横比。widthxheight>缩小尺寸大于相应宽度和/或高度参数的图像。看来-resize 140应该将宽度调整为140,同时保持与高度的纵横比,额外的>和^给聚会带来了什么?
标签: batch-file for-loop if-statement cmd