首页 > 解决方案 > Powershell 对两个字段进行排序并从 CSV 获取最新信息

问题描述

我正在尝试找到一种按两个字段对 CSV 进行排序并仅检索最新项目的方法。

CSV 字段:时间、计算机、类型、域。

有效的项目在下面,但由于 CSV 的规模而速度很慢,我觉得有更好的方法。

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

标签: powershellsortingunique

解决方案


正如 Lee_Dailey 所建议的那样,您可能会更好地使用 a hashtableGroup-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
  }
}

推荐阅读