I'm pulling 'down device' data from a network monitor via API using PowerShell
I'm struggling with how to reference the hostname value to add it to a variable. I'm after a list of hostnames of down devices.
In this case, there is only one host but obviously, there can be more than one with various IDs.
$user = 'user'
$pass = 'password'
$pair = "$($user):$($pass)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$Headers = @{
Authorization = $basicAuthValue
}
$webData = Invoke-RestMethod -Method Get -Uri 'http://fqdn/api/v0/devices/?status=0' -ContentType application/json -Headers $Headers # -OutFile c:\data\Config.html
#$webData= $webData | ConvertTo-Json
$webData | ForEach-Object {$_.devices} | Select -Property $_.hostname
Resulting Data from Powershell
201
---
@{device_id=201; poller_id=0; hostname=lonts01.local; sysName=lonts01.local; snmp_authname=;
Direct output of $webData without the -ContentType
{"status":"ok","count":3,"devices":{"201":{"device_id":"201","poller_id":"0","hostname":"lonts01.local","sysName":"lonts01.local",...
CodePudding user response:
This is a typical example where you need the JSON subkeys' name if you want to access the underlying object, as you cannot expand them without being named explicitly.
Notice that i am fetching the keys' value (name) first then using it to expand the object.
$webData.devices | Get-Member -MemberType NoteProperty | ForEach-Object {
$key = $_.Name
$webData.devices.$key.hostname
}