无法过滤对象集合以仅选择具有最新日期的对象 [英] Unable to filter collection of objects to select only those with latest date
问题描述
我有一个名为$items
的对象的集合:
I have a collection of objects named $items
:
我想根据FullName
属性将$items
过滤为不包含重复项,但将唯一的对象作为具有最新日期的对象.
I want to filter $items
down to not contain duplicates according to the FullName
property but have the unique object be the one with the latest date.
因为我不知道该怎么做,所以我的解决方案方法是首先创建一个新对象,该对象仅包含名称为$duplicateItems
的FullName
属性形式的重复项:
Since I couldn't figure out how to do that my solution approach was to first create a new object that only contains the duplicates in the form of the FullName
property named $duplicateItems
:
$arrDuplicates = @{}
$duplicateItems = foreach ($row in $restoreItems.FullName) {
if ($arrDuplicates.ContainsKey($row) -and $arrDuplicates[$row] -lt 2) {
$row
}
$arrDuplicates[$row] += 1
}
然后我尝试遍历$items
,如果当前$item.FullName
存在于$duplicateItems
中,则选择具有最新DeletedDate
的对象并还原它:
Then I tried to loop through $items
and if the current $item.FullName
exists in $duplicateItems
select the object with the latest DeletedDate
and restore it:
foreach ($item in $items) {
if ($item.FullName -in $duplicateItems) {
$filteredItem = $items | Where-Object {$_.FullName -eq $item.FullName} | Sort-Object DeletedDate | Select-Object -Last 1
$filteredItem.Restore()
}
$items = items | Where-Object {$_.FullName -ne $item.FullName}
}
我以为如果使用$items = items | Where-Object {$_.FullName -ne $item.FullName}
部分,则循环只会对唯一对象执行$filteredItem.Restore()
,而不会对所有$items
起作用.
I thought if I used the $items = items | Where-Object {$_.FullName -ne $item.FullName}
part the loop would only do $filteredItem.Restore()
on the unique objects and not all of $items
.
我敢肯定,有一种更简便的解决方案,可以根据FullName
属性将$items
过滤为不包含重复项,但将唯一的对象作为具有最新日期的对象.
I'm sure there's a way easier solution to filter $items
down to not contain duplicates according to the FullName
property but have the unique object be the one with the latest date.
推荐答案
Group the files by their full name, then select the most recent file from each group:
$restoreItems | Group-Object FullName | ForEach-Object {
$_.Group | Sort-Object DeletedDate | Select-Object -Last 1
}
这假设时间戳记是DateTime
对象.正如LotPings在注释中指出的那样,实际上它实际上应该是一个字符串,您需要首先将其解析为DateTime
对象,否则排序顺序将不正确.
This assumes that the timestamp is a DateTime
object. Should it actually be a string you need to parse it to a DateTime
object first, as LotPings pointed out in the comments, otherwise the sort order won't be correct.
这篇关于无法过滤对象集合以仅选择具有最新日期的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!