powershell - Powershell 对两个字段进行排序并从 CSV 获取最新信息
问题描述
我正在尝试找到一种按两个字段对 CSV 进行排序并仅检索最新项目的方法。
CSV 字段:时间、计算机、类型、域。
有效的项目在下面,但由于 CSV 的规模而速度很慢,我觉得有更好的方法。
$sorted = $csv | Group-Object {$_.computer} | ForEach {$_.Group | Sort-Object Time -Descending | Select-Object -First 1}
解决方案
正如 Lee_Dailey 所建议的那样,您可能会更好地使用 a 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
}
}
推荐阅读
- go - Golang - CSRF 令牌不匹配
- ios - 理解 Swift App 中的 SVG 变换矩阵
- python - 如何在python中以给定频率迭代时间戳
- python-3.x - 有人能告诉我如何纠正我的 python 代码中的语法错误和格式吗?我的输出一直说“SyntaxError:无效语法”
- r - 在 R 中,如何根据特定的行/列标准有选择地将一个单元格“复制并粘贴”到另一个单元格中?
- css - React Native 外部样式表不更新组件
- api - MarketStack API 仅返回 IEXG 交换数据
- kaggle - 从 kaggle 下载后文本文件减少(8GB 到 1GB)
- sql - SQL Server - 更改列长度会导致附带损害?
- python - 如何为每一行创建 HTML 表格按钮并将第一列的值输入到 Flask 函数进行查询