7

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

1 Answer 1

9

It is as trivial as

foreach($obj in $myCustomObject.departments)
{
    Write-Host ("Got" + $obj.department)
}
Sign up to request clarification or add additional context in comments.

1 Comment

wow. Cheers for the very simple explanation. I feel a bit silly for asking now :). Works like a charm. Duncs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.