powershell - 我有一个文件夹,其中包含多个包含图像的文件夹。我想根据尺寸过滤图像
问题描述
此代码正确显示 ImageName 和 FolderName,但 Dimension 保持空白。正确显示的数据未保存在 csv 文件中。
此外,如果基于维度的条件不起作用。
#-----------powershell script------------
foreach ($folder in $Folders) {
$Images = Get-ChildItem -Path $Folder -Filter *.png
$Results = @()
foreach ($image in $Images) {
$dimensions = $image.Dimensions
# $dimensions = "$($image.Width) x $($image.Height)"
If ($dimensions -ne '1000 x 1000') {
$Results += [pscustomobject]@{
ImageName = $image
FolderName = $Folder
Dimension = $dimensions
}
}
}
$Results | FT -auto
# $ExcelData= Format-Table -property @{n="$image";e='$Folder'}
$Results | Export-csv "C:\Users\M1036098\Documents\Imagelessthan1000pi.txt" -NoTypeInformation
}
输出中的维度属性保持空白
解决方案
所以让我们回顾一下为什么这不起作用。Get-ChildItem
带回对象System.Io.FileInfo
System.IO.FileIonfo我们可以从 Microsoft 看到没有名为Dimensions 的方法或属性。
那么让我们得到这些尺寸......
首先,我们要将图像加载到内存中并获取大小。
$Folders = @("C:\Test")
$Folders | %{
$Folder = $_
Get-ChildItem -Path $_ -Filter *.png | %{
try{
$Image = New-Object System.Drawing.Bitmap "$($_.FullName)"
[pscustomobject]@{
ImageName = $_.Name
FolderName = $Folder
Dimension = "$($Image.Height) x $($Image.Width)"
}
}catch{
}
} | ?{
$_.Dimension -ne "1000 x 1000"
}
}
输出看起来像
ImageName FolderName Dimension
--------- ---------- ---------
Test1.png C:\Test 1440 x 2560
Test2.png C:\Test 1200 x 1200
编辑:为 Sonam 添加功能。根据发布的答案。
function Get-ImageDimension([string]$Path, [array]$ImageExtensions, [array]$ExcludeDimensions){
Get-ChildItem -Path $Path -Include $ImageExtensions -Recurse | foreach-object{
try{
$image = [Drawing.Image]::FromFile($_);
[pscustomobject]@{
ImageName = $_.Name
FolderName = $_.DirectoryName
Dimension= "$($image.Width) x $($image.Height)"
}
}catch{
}
} | ?{
$ExcludeDimensions -notcontains $_.Dimension
}
}
Get-ImageDimension C:\Test\ -ImageExtensions *.png -ExcludeDimensions "1000 x 1000" | export-csv C:\Test\Test.csv
推荐阅读
- spring-boot - Jprofiler 不会在应用程序崩溃时分离
- c++ - 我可以使用 cmake/make 编译所有且仅编译我使用的 cpp/hpp 文件吗?
- r - 如何解决这个与原子向量有关的 R 错误消息?
- javascript - 无法在 Angular 7 中使用 D3 条形图读取未定义的属性“地图”
- google-app-maker - 如何通过代码样式化不同类型输入控件的值?
- deep-learning - 在 OpenNMT-py 中的翻译过程中获得对齐/注意
- moodle - 如何将scorm播放器与Moodle数据库集成
- javascript - force:recordData 在快速操作上不起作用
- java - 在spring MVC中验证实体类是否包含子类
- php - 如何使用正则表达式获取包含所有图像数字和图像字母的数组?