Home > Software engineering >  Group a csv duplicate column
Group a csv duplicate column

Time:11-12

I am kind of stuck with grouping and exporting a csv column with duplicate values of daily machine status. There will be only two duplicate values per machine.

hostname  status   
ABC         up      
DEF         up      
GHI         down    
ABC         down    
DEF         up      
GHI         up      

I am looking to get

hostname  status_morning   status_evening
ABC          up               down 
DEF          up                 up
GHI          down               up
$groups = import-csv .\machine-status.csv | group-object hostname
foreach($group in $groups){
Select-Object @{Name='Hostname'   ;Expression={$_.Values[0]}},
               @{Name='status_morning';Expression={$_.Values[1]}},
              @{Name='status_evening' ;Expression={$_.Values[2]}}

}

CodePudding user response:

There must be other simple ways, but the following code works.

$csv = Import-csv C:\PS\stack.csv | Group-Object 'HostName'
$csv | Select-Object 'Name',@{ n='Morning_status';e={$_.Group.status[0]}},@{ n='Evening_status';e={$_.Group.status[1]}}
  • Related