将属性添加到数组

Add properties to array

假设我有一个对象数组:

    $data = @(
   [pscustomobject]@{Id1='1';Id2=51213412;ID3='00:01:00'}
   [pscustomobject]@{Id1='1';Id2=51213412;ID3='00:02:00'}
   [pscustomobject]@{Id1='1';Id2=51213412;ID3='00:04:00'}
   [pscustomobject]@{Id1='1';Id2=51213412;ID3='00:04:00'}
   [pscustomobject]@{Id1='1';Id2=51213412;ID3='00:02:00'}
   [pscustomobject]@{Id1='2';Id2=11112314;ID3='00:01:00'}
   [pscustomobject]@{Id1='2';Id2=11112314;ID3='00:02:00'}
   [pscustomobject]@{Id1='2';Id2=11112314;ID3='00:03:00'}
   [pscustomobject]@{Id1='2';Id2=11112314;ID3='00:01:00'}
   [pscustomobject]@{Id1='3';Id2=12512521;ID3='00:01:00'}
   [pscustomobject]@{Id1='2';Id2=11112314;ID3='00:02:00'}
   [pscustomobject]@{Id1='4';Id2=42112521;ID3='00:01:00'}
   [pscustomobject]@{Id1='2';Id2=11112314;ID3='00:03:00'}
   [pscustomobject]@{Id1='3';Id2=12512521;ID3='00:02:00'}
   [pscustomobject]@{Id1='4';Id2=42112521;ID3='00:02:00'}
   [pscustomobject]@{Id1='1';Id2=51213412;ID3='00:03:00'}
   [pscustomobject]@{Id1='4';Id2=42112521;ID3='00:01:00'}
   [pscustomobject]@{Id1='3';Id2=12512521;ID3='00:05:00'}
   [pscustomobject]@{Id1='4';Id2=42112521;ID3='00:03:00'}
   [pscustomobject]@{Id1='3';Id2=12512521;ID3='00:01:00'}
   [pscustomobject]@{Id1='2';Id2=11112314;ID3='00:02:00'}
   [pscustomobject]@{Id1='4';Id2=42112521;ID3='00:01:00'}
   [pscustomobject]@{Id1='2';Id2=11112314;ID3='00:03:00'}
   [pscustomobject]@{Id1='3';Id2=12512521;ID3='00:02:00'}
   [pscustomobject]@{Id1='3';Id2=12512521;ID3='00:04:00'}
   [pscustomobject]@{Id1='1';Id2=51213412;ID3='00:05:00'}
   [pscustomobject]@{Id1='4';Id2=42112521;ID3='00:01:00'}
   [pscustomobject]@{Id1='3';Id2=12512521;ID3='00:05:00'}
   [pscustomobject]@{Id1='5';Id2=53252352;ID3='00:01:00'})

我想转换成属性 ID3,也就是只显示分钟的时间,这样我最终可以对它们进行求和。我找到了一个可以将其转换为分钟的代码:

$minutes = foreach ($mins in $data.ID3) {
$TimeSpan = [System.TimeSpan]::Parse($mins)
[System.Math]::Round($TimeSpan.TotalMinutes,0)}

但现在我在 $minutes 变量中得到了结果。用转换值替换 ID3 值的最快方法是什么?

根据现有 属性:

的值,使用计算 属性 表达式 Select-Object 到 select 新“列”
$data |Select-Object ID1,ID2,ID3,@{Name='Minutes';Expression={[math]::Round([timespan]::Parse($_.ID3).TotalMinutes, 0)}}

这将为每个输入对象创建一个新对象,每个对象都具有输入对象的 3 个属性和一个新的 属性 Minutes 以及已解析的值

如果您想“覆盖”现有的 ID3 属性,只需将其从 属性 名称列表中省略,并将其作为计算出的 [=22] 的名称提供=] 改为:

$data |Select-Object ID1,ID2,@{Name='ID3';Expression={[math]::Round([timespan]::Parse($_.ID3).TotalMinutes, 0)}}

如果你想更新对象的值,你可以像这样枚举它们并重新分配它们:

foreach($i in $data) {
    $i.ID3 = ([timespan] $i.ID3).Minutes
}

但是,既然你提到你想要它们的总和,你可能只是在寻找这个:

[timespan]::FromMilliseconds(
    [System.Linq.Enumerable]::Sum(
        [int[]] ([timespan[]] $data.ID3).TotalMilliseconds
    )
).TotalMinutes