我有一个哈希表数组,如下所示:
$hashtable1 = @{}
$hashtable1.name = "aaa"
$hashtable1.surname =@()
$hashtable1.surname += "bbb"
$hashtable2 = @{}
$hashtable2.name = "aaa"
$hashtable2.surname =@()
$hashtable2.surname += "ccc"
$hashtable3 = @{}
$hashtable3.name = "bbb"
$hashtable3.surname = @()
$hashtable3.surname += "xxx"
$A = @($hashtable1; $hashtable2; $hashtable3)
我需要遍历数组,并且需要根据 hashtable[].name 找出重复项
然后我需要将这些 hashtable.surname 分组为 hashtable[].surname ,以便结果将是一个哈希表数组,该数组将所有姓氏分组:
$hashtable1.name = "aaa"
$hashtable1.surname = ("bbb","ccc")
$hashtable3.name = "bbb"
$hashtable3.surname = ("xxx")
我正在考虑迭代到空数组
+
我找到了这个链接:
powershell compare 2 arrays output if match
但我不确定如何访问哈希表的元素。
我的选择:
- 我想知道 -contain 是否可以做到这一点。
- 我已经阅读过有关比较对象的内容,但我不确定是否可以这样做。 (现在看起来有点吓人)
我使用的是 PS5。
感谢您的帮助, 紫菀
最佳答案
您可以使用脚本 block 按名称对数组项进行分组,如下所示。 分组后,您可以轻松构建输出来执行您想要的操作。
#In PS 7.0+ you can use Name directly but earlier version requires the use of the scriptblock when dealing with arrays of hashtables.
$Output = $A | Group-Object -Property {$_.Name} | % {
[PSCustomObject]@{
Name = $_.Name
Surname = $_.Group.Surname | Sort-Object -Unique
}
}
这里是输出变量内容。
Name Surname
---- -------
aaa {bbb, ccc}
bbb xxx
注意
PS 7.0 中进行了改进,允许您在哈希表数组的 Group-Object 中简单地使用属性名称(例如:Name
),就像对任何其他数组类型所做的那样。但对于早期版本,必须通过在脚本 block 中传递属性来访问这些特定数组,如下所示:{$_.Name}
引用文献
Dr Scripto - Use a Script block to create custom groupings in PowerShell
关于arrays - Powershell根据属性值比较2个哈希表数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68776688/