我试图列出所有宽度为650的图片的路径,预期的结果是:
C:\test\650-width-picture1.png
C:\test\650-width-picture2.jpg
C:\test\subfolder\650-width-picture3.jpg
除此之外,我尝试了这个旧主题的解决方案:通过 Powershell 进行智能图像搜索
Get-Image.ps1
,我尝试了以下命令:PS C:\test> Get-ChildItem -Filter *.png -Recurse | .\Get-Image | ? { $_.Width -eq 650 } | ft fullname
但是对于每个文件,它都会返回以下错误:
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
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 }
仅返回图像信息,无法获取路径。因此在末尾添加“| ft fullname”不会返回任何内容。
作为 Powershell 的新手,我很难进一步了解。有人可以帮我吗?
尝试这样做,添加注释以帮助您理解逻辑:
# 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