Powershell сортирует два поля и получает последние новости от CSV - PullRequest
0 голосов
/ 15 ноября 2018

Я пытаюсь найти способ сортировки CSV по двум полям и получить только последний элемент.

Поля CSV: время, компьютер, тип, домен.

Пункт, который работает ниже, но медленный из-за масштаба CSV, и я чувствую, что есть лучший способ.

$sorted = $csv | Group-Object {$_.computer} | ForEach {$_.Group | Sort-Object Time -Descending | Select-Object -First 1}

1 Ответ

0 голосов
/ 16 ноября 2018

Как предполагает Lee_Dailey, вам, скорее всего, повезет больше с hashtable, Group-Object (если не используется с параметром -NoElement) довольно медленный и требует много памяти.

самый быстрый путь с макушки головы был бы примерно таким:

# use the call operator & instead of ForEach-Object to avoid overhead from pipeline parameter binding
$csv |&{
  begin{
    # create a hashtable to hold the newest object per computer 
    $newest = @{}
  }
  process{
    # test if the object in the pipeline is newer that the one we have
    if(-not $newest.ContainsKey($_.Computer) -or $newest[$_.Computer].Time -lt $_.Time){
      # update our hashtable with the newest object
      $newest[$_.Computer] = $_
    }
  }
  end{
    # return the newest-per-computer object
    $newest.Values
  }
}
...