Unable to filter collection of objects to select only those with latest date

邮差的信 提交于 2020-01-03 18:38:59

问题


I have a collection of objects named $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.

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 FullNameproperty named $duplicateItems:

$arrDuplicates = @{}
$duplicateItems = foreach ($row in $restoreItems.FullName) {
  if ($arrDuplicates.ContainsKey($row) -and $arrDuplicates[$row] -lt 2) {
    $row
  }
  $arrDuplicates[$row] += 1
}

Then I tried to loop through $items and if the current $item.FullName exists in $duplicateItems select the object with the latest DeletedDateand 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}
}

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.

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.


回答1:


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
}

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.




回答2:


I'm guessing $items is a PowerShell Object and the blurred out information contains the same strings. You could try:

$items | Sort-Object -Property DeletedDate,Name -Unique 

If the order is not right, try

$items | Sort-Object -Property DeletedDate,Name -Unique -Descending

Basically you just need to sort on two properties, and then select the unique values.



来源:https://stackoverflow.com/questions/51421260/unable-to-filter-collection-of-objects-to-select-only-those-with-latest-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!