我有一组名为 $items
的对象:
我要过滤$items
根据 FullName
不包含重复项属性,但唯一的对象是具有最新日期的对象。
由于我不知道该怎么做,因此我的解决方法是首先创建一个新对象,该对象仅包含 FullName
形式的重复项。属性命名 $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
并恢复它: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
.我相信有一种更简单的方法来过滤
$items
根据 FullName
不包含重复项属性,但唯一的对象是具有最新日期的对象。
最佳答案
Group文件的全名,然后从每个组中选择最新的文件:
$restoreItems | Group-Object FullName | ForEach-Object {
$_.Group | Sort-Object DeletedDate | Select-Object -Last 1
}
这假设时间戳是
DateTime
目的。如果它实际上是一个字符串,您需要将其解析为 DateTime
首先是对象,正如 LotPings 在评论中指出的那样,否则排序顺序将不正确。
关于powershell - 无法过滤对象集合以仅选择具有最新日期的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51421260/