Forum Discussion

DeepakMhaskar's avatar
DeepakMhaskar
Copper Contributor
Nov 11, 2019

How to output as csv from invoke-restmethod

output result in csv format for Invoke-restmethod.

  • Kevin_Morgan's avatar
    Kevin_Morgan
    Iron Contributor

    DeepakMhaskar 

     

    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 = "https://graph.microsoft.com/v1.0/users"
    $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.

Resources