arrays - Powershell根据属性值比较2个哈希表数组

标签 arrays powershell multidimensional-array iteration hashtable

我有一个哈希表数组,如下所示:

$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

但我不确定如何访问哈希表的元素。

我的选择:

  1. 我想知道 -contain 是否可以做到这一点。
  2. 我已经阅读过有关比较对象的内容,但我不确定是否可以这样做。 (现在看起来有点吓人)

我使用的是 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}

引用文献

MSDN - Group_Object

SS64 - Group Object

Dr Scripto - Use a Script block to create custom groupings in PowerShell

关于arrays - Powershell根据属性值比较2个哈希表数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68776688/

相关文章:

javascript - 在javascript中使用reduce或filter计算对象的数量

c++ - 如何将 16 位值数组转换为 base64?

javascript - 为什么我的函数不将 json 文件转换为数组 json

arrays - PowerShell 杀死多个进程

powershell - 通过 Powershell 将扩展属性添加到 Azure Active Directory 用户

string - 如何将字符串 append 到数据集中的其他字符串?

类类型对象的 Powershell 列表

javascript - 如何遍历多维关联javascript数组?

C 打印二维数组

php - 根据另一个查找/映射数组替换数组中的键