Royston
Royston

Reputation: 598

Splitting groups of CSV ROW's into separate CSV's OR Variables

$groups = Get-Content c:\devices.csv | Group {$_.Substring(0,3)}| %{$_.Group; ""}



    AAAGroup1,192.168.1.1
    AAAGroup1,192.168.1.2

    BBBGroup2,192.168.2.1
    BBBGroup2,192.168.2.2

    CCCGroup3,192.168.3.1
    CCCGroup3,192.168.3.2

I have searched far and wide and can only find solutions based on column selections To output the above data to either a separate variable per group or separate CSV file. Technically, there's a space in between each group in terms of a spare row, that's it as far as i can see.

$groups = Get-Content c:\devices.csv | Group {$_.Substring(0,3)}| %{$_.Group; ""}

ForEach ($Group in $Groups)...

Upvotes: 1

Views: 1349

Answers (1)

user6811411
user6811411

Reputation:

Provided you have a file devices.csv with headers Device,IPv4

The following script will add a calculated property named Group you can use to sort, output to a table and -GroupBy or whatever.

## Q:\Test\2018\07\10\SO_51267179.ps1

$data = Import-Csv '.\devices.csv' | 
  Select-Object Device,IPv4,@{n='Group';e={$_.Device.Substring(0,3)}}

$data | Format-Table -GroupBy Group

Sample output

   Group: AAA

Device    IPv4        Group
------    ----        -----
AAAGroup1 192.168.1.1 AAA
AAAGroup1 192.168.1.2 AAA

...snip...

To output each group to it's own .csv

$data = Import-Csv '.\devices.csv' | 
  | Group-Object {$_.Device.Substring(0,3)}| ForEach-Object {
    $_.Group | Export-Csv "$($_.Name).csv" -NoTypeInformation
}

Sample output:

> gc .\AAA.csv
"Device","IPv4"
"AAAGroup1","192.168.1.1"
"AAAGroup1","192.168.1.2"

Upvotes: 2

Related Questions