在数组中查找重复项

时间:2015-12-07 11:06:10

标签: arrays powershell duplicates

以下代码会生成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来检索它们那么简单。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

您可以使用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}