Displaying the contents of an array for each value inside a parent array

I’m an amateur with PS. Not new, but not proficient. I can usually take examples and modify to my needs. But this one has me stumped.

This is my example of what I’m trying to do:

Olympics object contains the properties Year (string), CountryResults (array)

CountryResults has properties Country (string), Medals (array)

Medals has properties Gold, Silver, Bronze containing the number for each.

I’m trying to output for each country (for this example I’m not concerned about the year):

CountryResults.Country CountryResults.Medals.Gold CountryResults.Medals.Silver CountryResults.Medals.Bronze

I can create:

$a = $Olympics.CountryResults | Select-Object Country,Medals
$b = $a | Select-Object -ExpandProperty Medals

$a would give me a result like
USA @{gold=15; silver=18; bronze=0}

$b would give me a result like
15 18 0

And that goes on for every different country.

What I’m trying to do is make it display in columns:
USA 15 18 0

I’ve tried joining the 2, but that just puts the results of $b after $a.

I’ve tried:

$a = $Olympics.CountryResults | Select-Object Country,Medals.gold,Medals.silver,Medals.bronze

But I get empty results for the Medals.

I’ve tried a For-Each to make a custom object, but that didn’t work (very good chance I wrote it wrong, so if this is the answer, don’t assume I wrote mine right and please leave an example response).

I’ve searched here and while some posts come close, they’re typically looking for a certain/specific value, so I haven’t been able to translate it to my need.

If you expand the property while selecting the other like this

$Olympics.CountryResults | Select-Object -Property Country -ExpandProperty Medals 

It will give you this output

Gold Silver Bronze Country
---- ------ ------ -------
  15     18      0 USA 

Is that what you’re after?

Yes! That’s what I needed. I didn’t realize you could combine Property and ExpandProperty in the same Select-Object. I changed it slightly so I could reorder the columns. That actually negated the need for ExpandProperty. Here’s what I ended up with in case anyone comes across this post with the same question:

$Olympics.CountryResults | Select-Object -Property Country, @{
      Name='Gold';
      Expression={ $_.Medals.gold }
	  },@{
      Name='Silver';
      Expression={ $_.Medals.silver }
	  },@{
      Name='Bronze';
      Expression={ $_.Medals.bronze }
	  } | ft
1 Like

That’s another great way to do it. It’s called calculated expressions or calculated properties

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.