0

I am trying to iterate the result of a webrequest call through powershell

$response = Invoke-WebRequest -URI $apiUri -Method Get -UseBasicParsing
$response

Result:

StatusCode        : 200
StatusDescription : OK
Content           : {"tenants":[{"name":"default","active":true},{"name":"tenant1","active":true}]}
RawContent        : HTTP/1.1 200 OK
...

Using ConvertFromJson

$parsed = $response.Content | ConvertFrom-Json
$parsed

Result:

tenants : {@{name=default; active=True}, @{name=tenant1; active=True}}

Now, I want to list all the "name" value like this

Name
--------
default
tenant1

I've tried iterating it using this script but can't get the result:

$parsed | Select-Object -Property name | ForEach-Object {
    Write-Host $_.name
}

1 Answers1

0

The code below will output a table of names:

$json = '{"tenants":[{"name":"default","active":true},{"name":"tenant1","active":true}]}'

$data = $json | ConvertFrom-Json

$data.tenants | ft name

#name
#----
#default
#tenant1

If you want to capture them into a variable as an array you can use a feature called Member Enumeration:

$names = $data.tenants.name;

$names
#default
#tenant1
mclayton
  • 8,025
  • 2
  • 21
  • 26
  • Thanks! so im just missing the .tenants. I need to foreach it as i need to do something in each of the item.. $parsed.tenants | Select-Object -Property name | ForEach-Object { Write-Host $_.name #do something } – Linc Abela Nov 17 '20 at 22:59
  • @LincAbela - you don't really need the ```select-object``` - you can just do ```$data.tenants | foreach-object { write-host $_.name }``` – mclayton Nov 18 '20 at 12:29