Home > Blockchain >  PowerShell to query nested child element of hashtable
PowerShell to query nested child element of hashtable

Time:03-07

In PowerShell, I want to get a count of all sports that use balls. The challenge is that they're a level lower than I can access with a direct Where-Object query. Here's the hashtable:

$league = @{
   school = @{
      name = 'Lincoln High School' 
      levels = ('9','10','11','12')
      } 
   sports = @{
      football = @{ 
         coed = 'b'
         season = 'fall'
         balls = $true
      }
      hockey = @{ 
         coed = 'b'
         season = 'winter'
         balls = $false
      }
      lacrosse = @{ 
         coed = 'g'
         season = 'spring'
         balls = $true
      }
      swim = @{ 
         coed = 'c'
         season = 'winter'
         balls = $false
      }
   }
}

How do I fashion the query to skip to the balls? Each sport is named differently at the key level, and wildcards don't seem to work.

( $league.sports | Where-Object { $_.[?].balls -eq $true } ).count

I need something to bridge to the child element of the sport.

CodePudding user response:

Using .where(..):

($league['sports'].GetEnumerator().Where{$_.Value.Balls}).Count

Using Where-Object:

($league['sports'].GetEnumerator() | Where-Object {$_.Value.Balls}).Count

As you can see, both methods require the use of .GetEnumerator() method.

Another more verbose alternative:

$sports = $league['sports']
$sports.PSBase.Keys.Where{$sports[$_]['balls']}.Count
  • Related