“规范化”CSV文件

时间:2016-10-28 16:16:10

标签: arrays powershell csv

我有一个用于帮助台呼叫的CSV文件。根据它具有的更新次数,同一票证可能包含1,2或甚至5条记录。 (一个字段不同,所有其他字段都相同)。

我想采用大多数重复的记录并创建一条记录,并将差异连接到其中。在过去编程,但作为PowerShell的新手,我可以使用一些帮助。

所以,基于我之前提出的一个问题,这是我到目前为止所拥有的。假设这样的数据:

ID, Date, Comment
345, 1/1/16, Moss has reported a fire in the I/T Room
345, 1/1/16, Never mind, he has sent an e-mail about it.
346, 1/2/16, Someone on the 5th floor is complaining about a man under her desk.
347, 2/1/16, Jen says she has broken the Internet.
347, 2/1/16, Douglas is very angry, we need a fix ASAP!
347, 2/1/16, Roy was playing a joke on her.  Closing ticket.

我有以下代码:

$FileList  = Import-Csv "Call List.csv"
$incidents = $FileList | Group ID
foreach($group in $incidents)
{
    # What goes here?
}

如何从组中的第2行,第3行等处获取注释,将其连接到第一行中的注释,并将文件写出来?

2 个答案:

答案 0 :(得分:4)

Group-Object生成一个名称和组的对象,Group包含该组中的所有项目。您可以使用以下内容提取它们并创建一个新对象:

$incidents = $FileList | Group-Object ID | % {
    New-Object psobject -property @{
        ID = $_.Name
        Date = $_.Group[0].Date
        Comment = ($_.Group | Select -Expandproperty Comment) -Join "`n"
    }
}  

(未按我目前在Mac上测试)

答案 1 :(得分:1)

我首先会获得唯一ID的列表,例如:

$Ids = $FileList | Select-Object -ExpandProperty Id -Unique

然后我查看门票清单并制作一份报告"对于每个ID:

foreach($Id in $Ids){
  # Get all incident logs for this Id:
  $logs = $FileList | ?{$_.Id -eq $Id}

  $report = ""

  foreach($log in $logs){
    $report += $log.Date + ": " + $log.Comment + "; "
  }

  # Now you can write the text out
  $report | Out-File $Outfile -Append
}

希望能给你一个想法。

相关问题