Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConvertFrom-Json Loop Through Object

I am pretty new to PowerShell and have the following code:

$jsonResponse = @"
{
"departments":[{"id":81,"department":"Sales"},{"id":61,"department":"IT Support"}]
}
"@

$myCustomObject = $jsonResponse | ConvertFrom-Json

$myCustomObject.departments.department[0]
$myCustomObject.departments.department[1]

Which allows me to access elements of the customObject (converted from JSON).

What I need is the ability to loop through the object so I can access each element i.e.

object_loop
{
 $myCustomObject.departments.department[x]
}

where x is the loop increment.

Sorry of this is silly question but I have googled and can't find a simple example.

Cheers for any help.

Duncs

like image 850
dunkyduncs Avatar asked Apr 23 '15 14:04

dunkyduncs


1 Answers

It is as trivial as

foreach($obj in $myCustomObject.departments)
{
    Write-Host ("Got" + $obj.department)
}
like image 102
Erti-Chris Eelmaa Avatar answered Oct 17 '22 14:10

Erti-Chris Eelmaa