我对通过自定义属性搜索文件感兴趣。例如,我想查找所有具有特定尺寸的 JPEG 图像。有些东西看起来像
Get-ChildItem -Path C:\ -Filter *.jpg -Recursive | where-object { $_.Dimension -eq '1024x768' }
我怀疑这是关于使用 System.Drawing。怎么做?提前致谢
我对通过自定义属性搜索文件感兴趣。例如,我想查找所有具有特定尺寸的 JPEG 图像。有些东西看起来像
Get-ChildItem -Path C:\ -Filter *.jpg -Recursive | where-object { $_.Dimension -eq '1024x768' }
我怀疑这是关于使用 System.Drawing。怎么做?提前致谢
这实际上很容易做到,而且您对 System.Drawing 的直觉实际上是正确的:
Add-Type -Assembly System.Drawing
$input | ForEach-Object { [Drawing.Image]::FromFile($_) }
将其保存Get-Image.ps1
在路径中的某个位置,然后您就可以使用它了。
另一种选择是将以下内容添加到您的$profile
:
Add-Type -Assembly System.Drawing
function Get-Image {
$input | ForEach-Object { [Drawing.Image]::FromFile($_) }
}
这几乎是一样的。当然,添加一些花哨的东西,比如文档或者你认为合适的东西。
然后你可以像这样使用它:
gci -inc *.jpg -rec | Get-Image | ? { $_.Width -eq 1024 -and $_.Height -eq 768 }
请注意,您应该在使用后处理以这种方式创建的对象。
当然,您可以添加自定义Dimension
属性,以便对其进行过滤:
function Get-Image {
$input |
ForEach-Object { [Drawing.Image]::FromFile($_) } |
ForEach-Object {
$_ | Add-Member -PassThru NoteProperty Dimension ('{0}x{1}' -f $_.Width,$_.Height)
}
}
这是(几乎)单行的另一种实现:
Add-Type -Assembly System.Drawing
Get-ChildItem -Path C:\ -Filter *.jpg -Recursive | ForEach-Object { [System.Drawing.Image]::FromFile($_.FullName) } | Where-Object { $_.Width -eq 1024 -and $_.Height -eq 768 }
如果您需要多次运行此命令,我会推荐Johannes 的更完整的解决方案。