[英]Group-Object, get counts
Given a list with some duplicate items, I can use Group-Object -AsHashtable
and I get a hash table that seems to have keys with the item names, and the value is something I don't recognize.给定一个包含一些重复项目的列表,我可以使用Group-Object -AsHashtable
并得到一个 hash 表,该表似乎具有项目名称的键,而值是我不认识的。
So, given所以,给定
$array = [System.Collections.Generic.List[String]]@('A', 'B', 'C', 'B', "c", 'C')
$grouped = $array | Group-Object -AsHashTable
$grouped
will be $grouped
将是
Name Value
---- -----
A {A}
B {B, B}
C {C, c, C}
At which point I would have thought that $grouped['B'].Count
or $grouped.'B'.Count
would produce the correct count of 2. But I am getting 0. What am I missing?那时我会认为$grouped['B'].Count
或$grouped.'B'.Count
会产生正确的计数 2。但我得到 0。我错过了什么?
You're seeing a bug in Windows PowerShell that has since been fixed in PowerShell (Core) 7+ - see GitHub issue #6933 for details.您在Windows PowerShell中看到了一个错误,该错误已在PowerShell(核心)7+中修复 - 请参阅ZD3B7C9233CD04EBFEC0EEC9的详细信息。
Workaround : In Windows PowerShell, always combine -AsHashTable
with -AsString
, even if the input objects or grouping property values already are strings.解决方法:在 Windows PowerShell 中,始终将-AsHashTable
与-AsString
结合使用,即使输入对象或分组属性值已经是字符串。 Tip of the hat to Abraham Zinala .向亚伯拉罕·齐纳拉致敬。
PS> ('A', 'B', 'C', 'B', "c", 'C' | Group-Object -AsHashTable -AsString).B.Count
2 # OK, thanks to -AsString (not necessary in PowerShell 7+)
This bypasses the bug, which otherwise manifests as follows: the strings that are meant to become the hashtable keys are unexpectedly wrapped in invisible [psobject]
wrappers , which in turn prevents string-based key lookup.这绕过了该错误,否则该错误表现如下:旨在成为哈希表键的字符串意外地包装在不可见的[psobject]
包装器中,这反过来又阻止了基于字符串的键查找。
Note: The implication is that you cannot use -AsHashtable
in Windows PowerShell if you want the keys to be of a data type other than string (eg [int]
), because for such data types the invisible [psobject]
wrapping cannot be bypassed.注意:这意味着如果您希望键是字符串以外的数据-AsHashtable
(例如[int]
),则不能在 Windows PowerShell 中使用 -AsHashtable ,因为对于此类数据类型,无法绕过不可见的[psobject]
包装。
try the below (it worked for me, see pic)试试下面的(它对我有用,见图片)
$array = [System.Collections.Generic.List[String]]@('A', 'B', 'C', 'B', "c", 'C')
$grouped = $array | Group-Object -AsHashTable
$grouped.B
$grouped.B.Count
Write-Host $grouped.B.Count
$b = $grouped.B.Count
Write-Host "The Number of Values in Column B Is - $b"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.