0

I have a complex object that is populated from a JSON string.

I'm trying to loop through a nested object that has a variable in the name itself.

So if I do a Write-Host $aaa.bbb.ccc1ccc.ddd I get a valid object back.
if I do a Write-Host $aaa.bbb.ccc2ccc.ddd I get a valid object back.

If I set $i = 1 and I do

Write-Host $aaa.bbb.ccc$($i)ccc.ddd it will of course fail.

If I try get-variable -valueonly -name "aaa.bbb.ccc$($i)ccc.ddd" I get an error: Cannot find a variable with the name 'aaa.bbb.ccc1ccc.ddd'

to be honest I can't even do a get-variable -valueonly -name "aaa.bbb"

There are other objects like aaa.bbb.dddd. that I don't want.

If $i is [1..100] can someone show me how to loop through this object?

Thanks,

1 Answer 1

1

When using the . reference operator, since version 3.0, you can substitute an expandable string for any member reference:

$aaa.bbb."ccc${i}ccc".ddd

so in your example you could do:

1..2 |ForEach-Object { $aaa.bbb."ccc${i}ccc".ddd }
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, thank you. I've been beating my head against my keyboard for hours on this one.

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.