Return list of all servers (~2K) using API and pagination - what am I missing?

  • 22 October 2021
  • 6 replies
  • 162 views

Userlevel 2
Badge

I cobbled this together from several items in the Automox Labs and API documentation:


$orgID = "myorgid"
$apiKey = 'myapikeyhere'
$filepath = ‘.\ServerInventory.csv’

$page = 0
$limit = 500
$data = @()

Write-Output "Page"

while($true) {
$headers = @{"Authorization" = "Bearer $apiKey" }
$url = "https://console.automox.com/api/servers?$orgID?l=$limit&p=$page"
$response = (Invoke-WebRequest -Method Get -Uri $url -Headers $headers).Content | ConvertFrom-Json

Write-Output $page
$data += $response
$page += 1

if($response.count -lt $limit) {
break
}
}
$data | Group-Object display_name | Sort-Object name | Select-Object Count,name `
| Export-Csv -Path $filepath -NoTypeInformation

The result is that it produces a csv of 500 server names as I’d expect. When I change “$page” to “1” in the script (and change the csv output file name) and run it again, it produces a new, blank csv.


I’ve read this: About Automox API


and feel like I’m doing it correctly, but it seems like I may be missing something - or am just doing something wrong.


Thoughts?


6 replies

Userlevel 3
Badge

This is what I like to use to pull all devices. We have over 3k devices and it does it well.


$orgID = ""
$apiKey = ""

###### Get Devices
$pageindex = 0
$Items = New-Object -TypeName "System.Collections.ArrayList"
$headers = @{ "Authorization" = "Bearer $apiKey" }

Do {
$url = "https://console.automox.com/api/servers?o=$orgID&page=$pageindex"
$Devices =(Invoke-restmethod -Method Get -Uri $url -Headers $headers)
foreach ($Item in $Devices) {$Items += $Item}
$pageindex++
}
Until ($Devices.count -lt 500)
###
Userlevel 2
Badge

Thanks; I will give that a try!

Userlevel 3
Badge

Just note that your devices are all contained in the $Items object when its done.

Userlevel 2
Badge

How do you output that into a CSV?

Userlevel 3
Badge
$Items | Export-Csv -NoTypeInformation c:\temp\devices.csv
Userlevel 2
Badge

Your script ran fast and worked perfectly - thank you!

Reply