【问题标题】:Get latest value by date按日期获取最新值
【发布时间】:2019-02-19 18:14:18
【问题描述】:

我有按日期排序的 csv,例如:

15.02.2019;pc1;5;
15.02.2019;pc2;0;
16.02.2019;pc3;2;
16.02.2019;pc1;0;
17.02.2019;pc2;2;
18.02.2019;pc1;0;
18.02.2019;pc1;1;
18.02.2019;pc2;1;

我想按日期获取最新的有价值的 PC。一定是这样的:

pc2;1
pc1;1
pc3;2

我的代码:

$info=Import-Csv 'my_file.txt' -Header date,pc,value -Delimiter ';'
$deadline = (Get-Date).AddDays(-30)
$datas=$info | Where-Object {($_."date" -as [DateTime]) -gt $deadline} | Sort-Object {$_."date" -as [DateTime]} -Descending| Sort-Object -property pc -unique

输出是:

date       pc  value
----       --  -----
18.02.2019 pc1 0    
18.02.2019 pc2 1    
16.02.2019 pc3 2    

如何获得第一台最新的 PC 机智值?

【问题讨论】:

  • $datas | Select -first 1

标签: powershell sorting import-csv


【解决方案1】:

这似乎做了你想要的。 [咧嘴一笑]

唯一有点奇怪的是……

  • “CSV 文件中的虚假读取”
    那只是为了获取示例数据而无需创建文件。
  • 使用Group-Object.PC属性值对项目进行聚类

这是代码...

# fake reading in a CSV file
#    in real life, use Import-CSV
$InStuff = @'
15.02.2019;pc1;5;
15.02.2019;pc2;0;
16.02.2019;pc3;2;
16.02.2019;pc1;0;
17.02.2019;pc2;2;
18.02.2019;pc1;0;
18.02.2019;pc1;1;
18.02.2019;pc2;1;
'@ | ConvertFrom-Csv -Delimiter ';' -Header Date, PC, Value

$EU_DatePattern = 'dd.MM.yyyy'
$Deadline = [datetime]::Now.Date.AddDays(-30)

$Results = $InStuff |
    ForEach-Object {
        # my date format is yyyy-MM-dd, so the "-as [datetime]" fails
        $_.Date = [datetime]::ParseExact($_.Date, $EU_DatePattern, $Null)
        $_
        } |
    Where-Object {
        $_.Date -gt $Deadline
        } |
    Sort-Object -Property Date, Value |
    Group-Object -Property PC |
    ForEach-Object {
        [PSCustomObject]@{
            PC = $_.Name
            # the very last item in the ".Group" array will be
            #    - the newest
            #    - have the highest ".Value"
            Value = $_.Group[-1].Value
            }
        }

$Results

输出...

PC  Value
--  -----
pc2 1    
pc1 1    
pc3 2    

就个人而言,我会认真考虑保留每个项目的日期。

【讨论】:

  • @Damir - 不客气!很高兴帮助了一些人...... [grin]
猜你喜欢
  • 1970-01-01
  • 2021-11-19
  • 2011-09-14
  • 2016-02-10
  • 2019-03-13
  • 2012-02-17
  • 1970-01-01
  • 2016-07-07
  • 1970-01-01
相关资源
最近更新 更多