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.

3 Replies

  • gastone's avatar
    gastone
    Brass Contributor
    $user = "GastoneCanali"
    $csvPath = ".\$user-repos.csv"
    
    try {
        $repos = Invoke-RestMethod -Uri "https://api.github.com/users/$user/repos" `
                   -Headers @{'Accept'='application/vnd.github+json'; 'X-GitHub-Api-Version'='2022-11-28'}
        
        $repos | ForEach-Object {
            [PSCustomObject]@{
                Name = $_.name
                Description = $_.description
                Language = if($_.language){$_.language}else{"N/A"}
                Stars = $_.stargazers_count
                Forks = $_.forks_count
                Updated = ([datetime]$_.pushed_at).ToString("yyyy-MM-dd")
                URL = $_.html_url
            }
        } | Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8
        
        Write-Host "Exported $(Import-Csv $csvPath | Measure-Object).Count repos to $csvPath" -ForegroundColor Green
       
    }
    catch {
        Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
    }

    The process works because Invoke-RestMethod automatically converts a JSON API response into PowerShell objects. To get a CSV, you simply pass these objects to the Export-Csv cmdlet. Use the -NoTypeInformation parameter to create a clean file without the object type header. If you need to filter or reshape the data first, you can use Select-Object in the pipeline to choose specific properties before exporting.

  • 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