首页 > 解决方案 > 如何根据其属性删除cmd中的图像?

问题描述

我没有使用 cmd 脚本的经验,但我想做一件小事,即 在一个文件夹中删除不同尺寸的不是 1920x1080的图像。那里的每张宽度为 1920 像素的图像都绝对是 1920x1080 的图像。所以我做了这个脚本:

(for /r %%F in (*) do (
    set "width="
    set "height="
    for /f "tokens=1*delims=:" %%b in ('"%%Width%%:%%Height%%"') do (
        if %%~bF NEQ 1920 del "%%F"
    )
)

但它输出文件 sintax 名称不正确并且文件没有被删除。

提前致谢。

标签: windowsimagepowershellcmd

解决方案


在 PowerShell 中,您可以将文件作为System.Drawing.Image对象加载并从那里获取宽度和高度:

Add-Type -AssemblyName System.Drawing

$imagesToDelete = Get-ChildItem . |Where-Object {
  try {
    $pic = [System.Drawing.Image]::FromFile($_.FullName)
    # We only want images that are _not_ 1920px wide
    $pic.Width -ne 1920
  }
  catch{
    # Ignore errors (== probably not an image)
  }
  finally {
    # Clean up
    if($pic -is [IDisposable]){
      $pic.Dispose()
    }
  }
}

$imagesToDelete然后将包含宽度不同的所有图像文件1920,您可以继续删除Remove-Item

$imagesToDelete |Remove-Item

推荐阅读