DavidM
DavidM

Reputation: 227

Looping through complex object with a variable in the variable name

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,

Upvotes: 0

Views: 36

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

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 }

Upvotes: 1

Related Questions