-1

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 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.