Skip to content

Instantly share code, notes, and snippets.

@obsti8383
Last active December 17, 2023 02:17
Show Gist options
  • Save obsti8383/62dd361900f9adddc5ea3bce42676b7c to your computer and use it in GitHub Desktop.
Save obsti8383/62dd361900f9adddc5ea3bce42676b7c to your computer and use it in GitHub Desktop.
Generic Powershell Script for getting JSON output from a REST API
# examples:
# .\REST_GET_to_CSV_ps7.ps1 https://api.github.com/repos/powershell/powershell/issues x x
$ErrorActionPreference = "Stop"
$url = $Args[0]
$headerName = $Args[1]
$headerContent = $Args[2]
$maxRelLink = $Args[3]
$dataname = $Args[4]
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add($headerName, $headerContent)
$allData = New-Object System.Collections.ArrayList @()
$count = 1
do {
"Getting "+$url
$resultsPage = Invoke-WebRequest -UseBasicParsing -Method GET -Headers $header -Uri $url
$Content = ConvertFrom-Json $resultsPage.Content
if($dataname) {
foreach ($entry in $Content.$dataname) {
$allData.Add($entry) | Out-Null
}
} else {
foreach ($entry in $Content) {
$allData.Add($entry) | Out-Null
}
}
$url = $resultsPage.RelationLink.Next
$count = $count + 1
} while ($url -And $count -le $maxRelLink)
$allData | ConvertTo-Csv -Delimiter ";" | Out-File -FilePath results.csv -Encoding utf8
"Nr. of results: "+$allData.Count
#Requires -Version 7.0
# examples:
# .\REST_GET_to_CSV_ps7.ps1 https://api.github.com/repos/powershell/powershell/issues x x 5
$ErrorActionPreference = "Stop"
$url = $Args[0]
$headerName = $Args[1]
$headerContent = $Args[2]
$maxRelLink = $Args[3]
$dataname = $Args[4]
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add($headerName, $headerContent)
$results = (Invoke-RestMethod $url -FollowRelLink -MaximumFollowRelLink $maxRelLink -Headers $headers | ForEach-Object { $_ })
if($dataname){
$results.$dataname | ConvertTo-Csv -Delimiter ";" | Out-File -FilePath results.csv -Encoding utf8
} else {
$results | ConvertTo-Csv -Delimiter ";" | Out-File -FilePath results.csv -Encoding utf8
}
"Nr. of results: "+$results.Count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment