wolfymaster
8/26/2016 - 11:25 PM

PowerShell file to recursively rename and edit images in a directory based on their image dimensions.

PowerShell file to recursively rename and edit images in a directory based on their image dimensions.


# This gets the correct path to the directory of execution
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

# Create variable from passed argument in command line
$filePath = $args[0]

# Get FullPath of file
$fullpath = [System.IO.Path]::GetFullPath(($filePath))

Get-ChildItem -Recurse $fullpath |
ForEach-Object {

    # File is not this filename
    if ($_.BaseName -eq "filesize") {
        return
    }

    # File is a folder (shouldn't be any folder inside JPEG)
    if($_.GetType().FullName -eq "System.IO.DirectoryInfo") {
        return #I want to delete this entire folder
    }

    # File is an image
    if( $_.Extension -eq ".jpg") {

        # Get image object
        $img = [System.Drawing.Image]::FromFile($_.FullName)

        # Check Size and do something
        if($img.PhysicalDimension.Width -eq 1024) {
            $img.Dispose()
            Rename-Item $_.FullName "$($_.Directory.Parent.BaseName)-kelly-tooke-leather_$(Get-Random).jpg".Replace(" ","-")
        } elseif($img.PhysicalDimension.Width -eq 637) {
            $img.Dispose()
            Remove-Item $_.FullName
        }
        return
    }
    

}