Powershell for each in Json

Tony Cross
Tony Cross used Ask the Experts™
on
I have a json file which has some information in as:-
$json.Hardware.'Network Adapters'.'Network Adapter 1'.'MAC Address'
$json.Hardware.'Network Adapters'.'Network Adapter 2'.'MAC Address'
$json.Hardware.'Network Adapters'.'Network Adapter 3'.'MAC Address'
$json.Hardware.'Network Adapters'.'Network Adapter 4'.'MAC Address'
$json.Hardware.'Network Adapters'.'Network Adapter 5'.'MAC Address'

Open in new window


I need to pull out the information, so thought about using a for loop:-
for ($x=1; $x -le 10; $x++) {
    if ($json.Hardware.'Network Adapters'.'Network Adapter $x'.Type -contains 'Wired*') {
        Write-Host "MAC Wired - " $json.Hardware.'Network Adapters'.'Network Adapter $x'.'MAC Address'
    }
}

Open in new window


But it isnt working. Im assuming Im not concatinating the $x in the variable name correctly, but tried to put it outside the loop as a variable, but that doesnt work.

Any ideas?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
A string in single quotes is taken literally by PowerShell, there will be no expanding of variables or subexpressions inside the string.
Try it like this:
For ($x=1; $x -le 10; $x++) {
	if ($json.Hardware.'Network Adapters'."Network Adapter $($x)".Type -contains 'Wired*') {
		Write-Host "MAC Wired - $($json.Hardware.'Network Adapters'."Network Adapter $($x)".'MAC Address')"
	}
}

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial