powershellpowershell-2.0powershell-3.0powershell-4.0

PowerShell script to export Array in CSV format with Headers


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


Solution

  • 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