Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagepowershell
titleConnect to iQSonar, get number of devices
collapsetrue
# We use simple authentication, default login/password
$user    = "admin"
$pass    = "password"
$secpass = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user,$secpass)

#
# To find out how many devices there are, ask for the first device and look at the header for the device count
#
# offset=01 means start with first device. fetch_size=1 means only return one record.
$uri     = 'http://vm-mike-2k12a.iqdomain.com/api/v1/devices/?offset=01&fetch_size=1'
$r = Invoke-WebRequest $uri -Credential $credential

# $r.headers has HTML headers, $r.content has text content
$deviceCount = $r.headers.'X-fetch-count'

...

By default the REST API "/api/v1/devices" page will return 200 devices at a time. We can increase or decrease this using the "fetch_size" parameter. The PowerShell invoke-restmethod cmdlet will automatically parse the JSON result into a PowerShell object for us. We will grab the details for one host at a time so as not to use too much memory, and also to make the JSON object easier (no need for a nested loop).

There are two fields in the result we want, the first is "host_name", and the second is "self" which contains a link to the full details of the device.
We enclose the output of each field in quotes in case the data in the field from the server contains a comma. (Some CPU names do contain commas)

...

Code Block
collapse
languagepowershell
titleFor each device, get hostname, ram, cputrue
$count = 0
$uri_a = 'http://vm-mike-2k12a.iqdomain.com/api/v1/devices/?offset='
$uri_b = '&fetch_size=1'

# This is going to hold the CSV file, let's build the header row
$csv = @() 
$row = New-Object System.Object
$row | Add-Member -MemberType NoteProperty -Name "Host" -Value $null
$row | Add-Member -MemberType NoteProperty -Name "RAM" -Value $null
$row | Add-Member -MemberType NoteProperty -Name "CPU Type" -Value $null


while ($count -le $deviceCount)
{	
	# Build the URL
	$count = $count + 1
	$url =  -join ($uri_a, $count, $uri_b )
	$dev = Invoke-RestMethod $url -Credential $credential
	
	$row = New-Object System.Object
	# Put the hostname in to the row
	$row | Add-Member -MemberType NoteProperty -Name "Host" -Value $dev.host_name ; 
	# Get the link to the rest of the details	
	$url2 = $dev.self	
	$device = Invoke-RestMethod $url2 -Credential $credential
	
	$row | Add-Member -MemberType NoteProperty -Name "RAM" -Value device.total_memory_mb
	$row | Add-Member -MemberType NoteProperty -Name "CPU Type" -Value $device.cpu.cpu_model
	$csv += $row
	# display progress
	write-host "." -nonewline
}

...

Code Block
languagepowershell
collapsetitletrueSave the output
#
# Now the CSV is finished, let's save it as output.csv
#
$csv | Export-csv output.csv -NoTypeInformation

...