How to delete an image file based on its dimensions with PowerShell

I am trying to delete an image based on the dimensions of said image, but I’ve run into a problem.

I am trying to delete images whose length or width are less than 490 pixels. However, the code I have tried throws an error for every item. This is the error:

Remove-Item : Cannot remove item (file path): The process cannot access the file
'(file path)' because it is being used by another process.
At line:6 char:9
+         Remove-Item $_
+         ~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: ((file path):FileInfo) [Remove-Item], IOException
    + FullyQualifiedErrorId : RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand

Here is my code:

[Void][Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$(Get-ChildItem -Filter *.jpg).FullName | ForEach-Object { 
    $img = [Drawing.Image]::FromFile($_); 

    If (($img.Width -lt 490) -or ($img.Height -lt 490)) {
        Remove-Item $_
    }
}

I am not running any apparent processes that would be using the images. When using Handle64, it says that powershell.exe is using the files. Any help would be appreciated!

>Solution :

The $img object is keeping the file in use, so you need to dispose of that before you can delete the file:

Add-Type -AssemblyName System.Drawing

(Get-ChildItem -Filter '*.jpg' -File).FullName | ForEach-Object { 
    $img = [System.Drawing.Image]::FromFile($_)
    $w = $img.Width
    $h = $img.Height
    # get rid of the Image object and release the lock on the file
    $img.Dispose()
    If (($w -lt 490) -or ($h -lt 490)) {
        Remove-Item -Path $_
    }
}

Leave a Reply