aston_zh
aston_zh

Reputation: 6843

sort csv with new lines

I got my report with users and workstations. Now if a User has several workstations I want to have a separate line for each of his workstations. Always with Name, Surename, Workstation. At the end it should be exported as a report-new.csv.

CSV:

"Name","Surname","Workstation"
"John","Doe","PC001,PC005,PC100"
"Fonzarelli","Arthur","PC234,PC324"
"Tribbiani","Joey","PC999"

Script:

$report = Import-Csv "C:\Scripts\report.csv"

Foreach ($wst in $report) {

    If ($wst.Workstation -match ",") {

        New Line foreach Workstation? Export-Csv "C:\Scripts\report-new.csv" -NoTypeInformation
    }
}

Upvotes: 1

Views: 51

Answers (2)

iRon
iRon

Reputation: 23713

$Report | ForEach {ForEach ($ws in ($_.workstation -split ",")) {
    $_ | Select Name, SurName, @{Name = "Workstation"; Expression = {$ws}}}
} | Export-Csv "C:\Scripts\report-new.csv" -NoTypeInformation

Result:

Name       Surname Workstation
----       ------- -----------
John       Doe     PC001
John       Doe     PC005
John       Doe     PC100
Fonzarelli Arthur  PC234
Fonzarelli Arthur  PC324
Tribbiani  Joey    PC999

Upvotes: 1

Martin Brandl
Martin Brandl

Reputation: 58961

You can split the Workstation property by a comma and join it together using a newline. Example:

$report = Import-Csv "C:\Scripts\report.csv"

Foreach ($wst in $report) {

    ($wst.Workstation -split ',') -join [System.Environment]::NewLine
}

Upvotes: 0

Related Questions