PowerShell script to export Array in CSV format with Headers

55 Views Asked by At

I've below PS Script which connects to API and puts responses on an Array List. I'm struggling to convert Array List to CSV file and giving them a Column Header. Anyone got Idea how to this can be done on PowerShell?


$headers.Add("Authorization", "Bearer $access_token")

$response = Invoke-RestMethod -Uri $URL -Method GET -Headers $headers -DisableKeepAlive -Certificate $certx
$js1 = $response.workers.person.legalName.givenName| ConvertTo-Json -depth 1 
$js2 = $response.workers.person.legalName.familyName1| ConvertTo-Json -depth 1
$js3 = $response.workers.businessCommunication.emails.emailUri| ConvertTo-Json -depth 1 



@($js1;$js2;$js3) | Out-File "C:\Users\file2.json"  ```

Output of above script is as below
[
    "a",
    "b",
    "c"
]
[
    "d",
    "e",
    "f"
]
[
    "g",
    "h",
    "i"
]

However i would like to have output something like below.

CSV File

2

There are 2 best solutions below

0
Santiago Squarzon On BEST ANSWER

Seems like combining the different property values into a single object should do the trick:

$response.workers | ForEach-Object {
    [pscustomobject]@{
        Name    = $_.person.legalName.givenName
        Surname = $_.person.legalName.familyName1
        Email   = $_.businessCommunication.emails.emailUri
    }
} | Export-Csv path\to\file.csv -NoTypeInformation
0
Mathias R. Jessen On

For each desired row in the resulting CSV, construct a single object with property names corresponding to your column names - you can use Select-Object with calculated property expressions to create new objects with a given "shape":

$outputObjects = $response.workers |Select-Object @{Name='Name';Expression={$_.person.legalName.givenName}},@{Name='Surname';Expression={$_.person.legalName.familyName1}},@{Name='Email';Expression={$_.businessCommunication.emails.emailUri}}

Then pipe to Export-Csv to create a CSV file based on the data:

$outputObjects |Export-Csv path\to\output.csv -NoTypeInformation