Powershell将行转换为列

时间:2016-03-04 10:50:06

标签: csv powershell transpose

有人可以帮我将行转换成列。需要将MachineName转换为列。
必须对结束时间进行排序。

<#MachineName, TotalDataSizeBytes, ActualStartTime, EndTime,   FinalJobStatus
SERVER1, 322349304901, 28/02/2016 23:00:03, 29/03/2016 23:33:23, OK
SERVER1, 322349304902, 26/02/2016 23:00:03, 27/03/2016 23:33:23, OK
SERVER2, 322349304903, 28/02/2016 23:00:01, 29/03/2016 23:33:23, OK
SERVER2, 322349304904, 26/02/2016 23:00:01, 27/03/2016 23:33:23, OK
#>

$graph = Import-Csv d:\report3.csv | foreach {

  New-Object PSObject -prop @{
    EndTime = [DateTime]::Parse($_.EndTime);
    MachineName = $_.MachineName;
    TotalDataSizeBytes = $_.TotalDataSizeBytes
  }
} 

#Desired result in a csv file.

#EndTime,SERVER1,SERVER2
#27/03/2016 23:33:23,322349304902,322349304904
#29/03/2016 23:33:23,322349304901,322349304903


Edit1. Found a similar question:
http://stackoverflow.com/questions/33906500/powershell-csv-row-column-transpose-and-manipulation

1 个答案:

答案 0 :(得分:2)

首先找到所有相关的机器名称,我们以后需要这些名称:

$Rows = Import-Csv d:\report3.csv
$MachineNames = $Rows |Select-Object -ExpandProperty MachineName |Sort -Unique

接下来,按Endtime对所有条目进行分组,并将所有分组在一起的行中的值添加到单个对象中:

$ConsolidatedRows = $Rows |Group-Object EndTime |ForEach-Object {
    $NewRowProperties = @{ EndTime = [DateTime]::Parse($_.Name) }
    foreach($Row in $_.Group)
    {
        $NewRowProperties.Add($Row.MachineName,$Row.TotalDataSizeBytes)
    }
    New-Object psobject -Property $NewRowProperties
}

最后,使用我们之前获取的名称选择EndTime属性和所有MachineName特定属性:

$ConsolidatedRows |Select-Object @("EndTime";$MachineNames) |Export-Csv .\finalReport.csv -NoTypeInformation