在一个数组中查找重复项。

5
以下代码将返回一个Array
[Array]$Object = [PSCustomObject]@{
    P1 = 'Appel'
    P2 = 'Cherry'
    P3 = 'Appel'
    P4 = 'Banana'    
}
$Object += [PSCustomObject]@{
    P1 = 'Good'
    P2 = 'Bad'
    P3 = 'Good'
    P4 = 'Good'
}
$Object += [PSCustomObject]@{
    P1 = 'Green'
    P2 = 'Red'
    P3 = 'Green'
    P4 = 'Yellow'
}
$Object

这将生成:
P1         P2         P3       P4                          
--         --         --       --                          
Appel      Cherry     Appel    Banana                      
Good       Bad        Good     Good                        
Green      Red        Green    Yellow 

我正在尝试找出如何让它报告重复项,这种情况下期望的结果P1P3,因为它们都包含相同的信息:

P1      P3                       
--      --                       
Appel   Appel                    
Good    Good                     
Green   Green 

由于这些值不在同一个对象中,所以不能简单地使用Group-Object来检索它们。任何帮助将不胜感激。

类似于 if (!(Compare-Object $object.p1 $object.p3)) { echo duplicate } 这样的东西? - arco444
是的,arco444,这就是我现在正在尝试的东西。Compare-Object $Object.P1 $Object.P3 -IncludeEqual -ExcludeDifferent。我只需要弄清如何循环遍历集合以进行比较。 - DarkLite1
2个回答

6

您可以使用Group-Object命令来查找每个对象中重复的属性值,通过检查psobject.Properties属性中每个条目的值:

PS C:\> $Object |ForEach-Object {
    $_.psobject.Properties | Group-Object { $_.Value } | Format-Table
}

Count Name                      Group
----- ----                      -----
    2 Appel                     {string P1=Appel, string P3=Appel}
    1 Cherry                    {string P2=Cherry}
    1 Banana                    {string P4=Banana}


Count Name                      Group
----- ----                      -----
    3 Good                      {string P1=Good, string P3=Good, string P4=Good}
    1 Bad                       {string P2=Bad}


Count Name                      Group
----- ----                      -----
    2 Green                     {string P1=Green, string P3=Green}
    1 Red                       {string P2=Red}
    1 Yellow                    {string P4=Yellow}

谢谢Mathias让我找到正确的方向,但我真的需要比较所有3个值来确定它们是否全部匹配。 - DarkLite1
我还不太确定你在这里想实现什么。你的$Object数组中的三个对象之间都没有重复。 - Mathias R. Jessen
你说得对,这些值不在同一个对象中。我已经更新了原始帖子以使其更清晰。 - DarkLite1
是的,但是P4属性怎么办呢?它在第二个对象中有一个重复值。 - Mathias R. Jessen
我不关心那个,只有当所有三个属性值相等时,我才感兴趣。 - DarkLite1

4

最终弄清楚了:

$Props = $Object | Get-Member | ? MemberType -EQ NoteProperty | Measure-Object | Select-Object -ExpandProperty Count

$Result = for ($a = 1; $a -le $Props; $a++) {
    for ($b = 1; $b -le $Props; $b++) {
        if ($a -ne $b) {
            if (($R = Compare-Object ([String[]]$Object.("P$a")) ([String[]]$Object.("P$b")) -IncludeEqual -ExcludeDifferent).Count -eq 3) {
                $R.InputObject | Out-String
            }
        }
    }
}

$Result | Select-Object -Unique

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接