我被困在以下情况:我必须从CSV文件中获取信息。我使用Import-Csv导入了CSV。
我的原始数据如下:
45227;01.10.2018 03:24:00;Xxxx Xxxx Xxxxx x XX xxxxxxxxxxxxxx Xxxxx xxx Xxxxxxxxxxxxxxxxxxx;;3;XXXX;XXXX;XXX@XX.com;;;3.7;;其中包含3.7的列是感兴趣的值(“点”)。
下面是我的第一个问题->使用Import-Csv,powershell将把这些信息保存在[string]属性中。为了避免这种情况,我使用了以下一行:
| Select @{Name="Points";Expression={[decimal]$_.Points}}现在,我得到了一个Selected.System.Management.Automation.PSCustomObject-typed对象,它将该属性作为[decimal]包含。现在,我想总结一下所有被同一个电子邮件地址所使用的要点:
$Data[$Index].Points += (
$Imported_CSV | where {$_.Sender -eq $Imported_CSV_Unique.Sender} |
measure Points -sum
).Sum这似乎很好,但是如果我打开$Data[$Index] | gm,我就会得到这个:Points NoteProperty double Points=71301.6000000006
属性更改为[double]。我研究了一下,发现Powershell的GenericMeasureInfo.Sum属性只能将Nullable<Double>实例作为属性值返回。
我似乎产生了一个溢出的[double],因为所显示的数字完全错误。我想坚持十进制或整数,所以我有一个像71123.4之类的输出。
还有其他方法吗,所以我不需要使用(Measure-Object -sum).Sum?
提前感谢!
发布于 2019-03-17 12:58:22
首先,我将所有发件人的地址组合在一起,然后将它们分别加在一起:
Import-Csv .\data.csv |Group-Object Sender |ForEach-Object {
[pscustomobject]@{
Sender = $_.Name
SumOfPoints = ($_.Group |Measure-Object Points -Sum).Sum
}
}Measure-Object将自动将Points字符串转换为[double] --如果需要更高的精度,可以像以前一样手动转换为[decimal]:
Import-Csv .\data.csv |Select-Object Sender,@{Name="Points";Expression={[decimal]$_.Points}} |Group-Object Sender |ForEach-Object {
[pscustomobject]@{
Sender = $_.Name
SumOfPoints = ($_.Group |Measure-Object Points -Sum).Sum
}
}发布于 2019-03-17 14:23:25
像Mathias已经做的那样使用分组,下面是如何在不丢失十进制精度的情况下得到和,就像我以前评论过的那样:
# faking the Import-Csv here with a here-string.
# in real life, you would use: Import-Csv <yourdata.csv> -Delimiter ';'
$data = @"
Sender;Date;Description;Something;Number;Whatever;DontKnow;Email;Nothing;Zilch;Points;Empty;Nada
45227;01.10.2018 03:24:00;Xxxx Xxxx Xxxxx x XX xxxxxxxxxxxxxx Xxxxx xxx Xxxxxxxxxxxxxxxxxxx;;3;XXXV;XXXA;XXX@XX.com;;;3.7;;
45227;01.10.2018 03:24:00;Xxxx Xxxx Xxxxx x XX xxxxxxxxxxxxxx Xxxxx xxx Xxxxxxxxxxxxxxxxxxx;;3;XXXW;XXXB;XXX@XX.com;;;4.7;;
45226;01.10.2018 03:24:00;Xxxx Xxxx Xxxxx x XX xxxxxxxxxxxxxx Xxxxx xxx Xxxxxxxxxxxxxxxxxxx;;3;XXXX;XXXC;XXX@XX.com;;;4.777779;;
45225;01.10.2018 03:24:00;Xxxx Xxxx Xxxxx x XX xxxxxxxxxxxxxx Xxxxx xxx Xxxxxxxxxxxxxxxxxxx;;3;XXXY;XXXD;XXX@XX.com;;;4.8;;
45225;01.10.2018 03:24:00;Xxxx Xxxx Xxxxx x XX xxxxxxxxxxxxxx Xxxxx xxx Xxxxxxxxxxxxxxxxxxx;;3;XXXZ;XXXE;XXX@XX.com;;;4.9;;
"@ | ConvertFrom-Csv -Delimiter ';'
#get the two columns you need from the Csv and group them by Sender
$data | Select-Object Sender, Points | Group-Object Sender | ForEach-Object {
# add the 'Points' values as decimal
[decimal]$sum = 0
foreach ($value in $_.Group.Points) { $sum += [decimal]$value }
[PSCustomObject]@{
Sender = $_.Name
Sum = $sum
}
}上述产出如下:
发送者和
https://stackoverflow.com/questions/55205714
复制相似问题