【问题标题】:Batch File: Nested If/else in For loop批处理文件:在 For 循环中嵌套 If/else
【发布时间】: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


【解决方案1】:
  • 不要在 for 循环(代码块)中使用(伪)标签::。必要时使用 rem
  • for 循环变量~z 修饰符返回文件大小(以字节为单位)

:: Q:\Test\2018\05\10\SO_50281887.cmd
@echo off
SETLOCAL EnableDelayedExpansion
SET maxbytesize=25000
SET logfile=A:\JobLogs\PhotoCompression.log
ECHO Starting compression job at %date% %time% >> %logfile%

FOR /R "C:\My\Directory\" /D %%G IN (*
) DO Call :CheckFiles "%%~fG" || (
    PushD "%%~fG"
    magick mogrify -resize "140>^" -quality 75% -depth 8 -units PixelsPerInch -density 72x72 -strip "*.jpg"
    ECHO %%G has been compressed %date% %time% >> %logfile%
    PopD
)
:: Appends completed job status to logfile
ECHO Job is complete %date% %time% >> %logfile%
Exit

:CheckFiles
For %%F in (%~1\*.jpg) Do If %%~zF GTR %maxbytesize% Exit /B 1
:: No files are larger than 25Kb,
ECHO All files in %~1 are smaller than %maxbytesize% %date% %time% >> %logfile%
  • 此批处理从 start 迭代所有(子)文件夹
  • 调用一个检查所有 *.jpg 的子程序
  • 如果只有一个大于 maxbytesize 它会返回一个错误
  • 通过条件执行调用magick命令。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多