PowerShell查询哈希表的嵌套子元素

发布于 2025-01-11 09:13:18 字数 819 浏览 0 评论 0原文

在 PowerShell 中,我想统计所有使用球的运动。挑战在于它们的级别低于我可以通过直接Where-Object 查询访问的级别。这是哈希表:

$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
      }
   }
}

如何设计查询以跳到balls?每项运动在关键级别的命名都不同,并且通配符似乎不起作用。

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

我需要一些东西来连接这项运动的儿童元素。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深巷少女 2025-01-18 09:13:18

使用.where(..)

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

使用Where-Object

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

如您所见,这两种方法都需要使用.GetEnumerator() 方法

另一种更详细的替代方案:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文