Home > front end >  Powershell split Object[] into multiline CSV file
Powershell split Object[] into multiline CSV file

Time:10-07

I have a powershell array object that looks like this

Name    : Bob
Address : {adr1, adr2, adr3}
Phone   : 123

Name    : Alice
Address : {adr4, adr5, adr6}
Phone   : 456

I want to convert this object into a CSV file that should look like this:

"Name","Address","Phone"
"Bob","adr1","123"
"Bob","adr2","123"
"Bob","adr3","123"
"Alice","adr4","456"
"Alice","adr5","456"
"Alice","adr6","456"

if i use Export-Csv on the object the output looks like this:

"Name","Address","Phone"
"Bob","System.Object[]","123"
"Alice","System.Object[]","456"

How do i get my output to look like the expected one?

CodePudding user response:

You can create 1 new object per value in each object's Address property with a simple nested loop:

$data |ForEach-Object {
  foreach($adr in $_.Address){
    # create 1 new object per value in $_.Address
    $_ |Select Name,@{Name='Address';Expression={$adr}},Phone
  }
} |Export-Csv output.csv -NoTypeInformation
  • Related