1

I don't have experiences with cmd script, but I want to do a little thing that is deleting images with different dimensions that aren't 1920x1080 in just one folder. Every image there with 1920 px of Width is definetely a 1920x1080 image. So I made this script:

(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"
    )
)

But it's outputing that the file sintax name is incorrect and the files are not being deleted.

Thanks in advance.

dsenese
  • 143
  • 11
  • You might get more help if you add a powershell tag to your question. – somebadhat May 12 '20 at 13:58
  • Thanks @somebadhat, i'll do that! – dsenese May 12 '20 at 14:15
  • 1
    Try [these](https://stackoverflow.com/questions/26314980/powershell-delete-images-of-certain-dimensions) [answers](https://stackoverflow.com/questions/26314980/powershell-delete-images-of-certain-dimensions). If you get the solution working, you can post your own answer to the question too. – vonPryz May 12 '20 at 14:37
  • @vonPryz I'm actually using [this answer](https://stackoverflow.com/questions/18855048/get-image-file-dimensions-in-bat-file) to guideline me. But I couldn't adapt the code as I wanted. – dsenese May 12 '20 at 14:55

1 Answers1

3

In PowerShell you could load the file as a System.Drawing.Image object and get the width and height from there:

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 will then contain all image files with width different than 1920, you can proceed to delete with Remove-Item:

$imagesToDelete |Remove-Item
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Thank you Mathias. I will wait for some answer in cmd cause I already have a piece of code before this "delete image" on cmd. If I can't make it, I will change to Powershell and use your answer. Thank you. – dsenese May 12 '20 at 15:51
  • Thanks, Mathias! I changed my previous cmd script to Powershell and your code worked flawlessly. – dsenese May 12 '20 at 19:07
  • @dsenese That's great to hear, you're most welcome! I'd strongly suggest leaving batch scripts behind and start to embrace PowerShell in general (it's installed on Windows by default for more than 10 years now!) – Mathias R. Jessen May 12 '20 at 19:19