powershellimagefile-search

List Fullname of image files of certain width or height, on Powershell


I'm trying to list the paths of all pictures with a width of 650, the intended result would be:

C:\test\650-width-picture1.png
C:\test\650-width-picture2.jpg
C:\test\subfolder\650-width-picture3.jpg

Among other things, I tried solutions from this old topic: Smart image search via Powershell

  1. Using the Get-Image.ps1 described in the top solution, I tried the following command:
PS C:\test> Get-ChildItem -Filter *.png -Recurse | .\Get-Image | ? { $_.Width -eq 650 } | ft fullname

But for each file, it returns the following error:

Exception calling « FromFile » with « 1 » argument(s) : « 650-width-picture1.png »
At C:\test\Get-Image.ps1:3 : 27
+ $input | ForEach-Object { [Drawing.Image]::FromFile($_) }
+                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FileNotFoundException
  1. From the second solution of the same topic, the two-liner:
PS C:\test> Add-Type -Assembly System.Drawing
PS C:\test> Get-ChildItem -Filter *.png -Recurse | ForEach-Object { [System.Drawing.Image]::FromFile($_.FullName) } | Where-Object { $_.Width -eq 650 }

returns only the image info, and I cannot get the path. Thus adding "| ft fullname" at the end returns nothing.

As someone new to Powershell, I struggle to get any further. Could someone please help me?


Solution

  • Try with this, adding comments to help you understand the logic:

    # load the drawing namespace
    Add-Type -AssemblyName System.Drawing
    
    Get-ChildItem -Filter *.png -Recurse | ForEach-Object {
        # for each `.png` file
        try {
            # instantiate the image for this file
            $img = [System.Drawing.Image]::FromFile($_.FullName)
            # if the image's `.Width` is equal to 650
            if ($img.Width -eq 650) {
                # output the `FileInfo` instance (from `Get-ChildItem` output)
                $_
            }
        }
        finally {
            # lastly, if the image could be instantiated
            if ($img) {
                # dispose it
                $img.Dispose()
            }
        }
        # select the `.FullName` property from the `FileInfo` instance
    } | Select-Object FullName