How to output as csv from invoke-restmethod

Copper Contributor

output result in csv format for Invoke-restmethod.

2 Replies

Really depends on the output you are getting. Example query might help.



As @VasilMichev said, it depends on the type of the response received.

If you get a response in JSON format, the Powershell itself converts the JSON response into Powershell object (psobject), if the returned Powershell object is array, you can simply export it using Export-Csv command.

$apiUrl = ""
$response = Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Get

$users = $response.value
$users | Export-Csv -Path "C:\Users.csv" -NoTypeInformation
$users | Select displayName,userPrincipalName | Export-Csv -Path "C:\Users.csv" -NoTypeInformation

if your response is not in the required format, then you have to form required JSON string from the response and convert to ps object.