如何使用 PowerShell 根据尺寸删除图像文件

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

我正在尝试根据所述图像的尺寸删除图像,但我 运行 遇到了问题。

我正在尝试删除长度或宽度小于 490 像素的图像。但是,我尝试过的代码会为每个项目抛出错误。这是错误:

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

这是我的代码:

[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 $_
    }
}

我没有 运行宁任何明显的进程会使用这些图像。使用 Handle64 时,它表示 powershell.exe 正在使用这些文件。如有任何帮助,我们将不胜感激!

$img 对象使文件一直在使用中,因此您需要先处理掉它,然后才能删除文件:

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 $_
    }
}