Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Powershell split Object[] into multiline CSV file

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading