在数组中查找重复项并打印

时间:2019-06-07 13:34:16

标签: arrays powershell

我有以下代码:

cls
Get-Module -ListAvailable | Import-Module
Import-Module ActiveDirectory 
$Groups = Get-ADGroup -Filter {name -like 'XYZ'} | select name - 
ExpandProperty name
$i=0 
$tot = $Groups.count 
$Table = @()

$Record = @{
"Group Name" = ""
"Name" = ""
"username" = ""
}

Foreach ($Group in $Groups) {
#// Set up progress bar 
$i++ 
$status = "{0:N0}" -f ($i / $tot * 100) 
Write-Progress -Activity "Exporting AD Groups" -status "Processing 
Group $i of $tot : $status% Completed" -PercentComplete ($i / $tot * 
100) 
$Arrayofmembers = Get-ADGroupMember -identity $Group -recursive | 
select name, SamAccountName
foreach ($Member in $Arrayofmembers) {
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."username" = $Member.SamAccountName
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord

}
 }
Write-Host $Table

效果很好,但是我想列出$ Record中的所有重复项。“ Name” = $ Member.name与特定组,例如:

username = barry在GROUP XYZ中重复

我已经尝试了以下方法:

ForEach ($Element in $Table)
{
If (($Table -match $Element).count -gt 1)
{
    "Duplicates detected" 

}
}

2 个答案:

答案 0 :(得分:3)

最简单的答案是仅将$Table传递到Group-Object并过滤出末尾计数大于1的组,如下所示:

$Table | Group 'Group Name','Name' | Where{$_.Count -gt 1}

如果您希望在循环的中间进行此操作,可以对Get-ADGroupMember的结果进行分组,但我认为这样做可能会更快。

答案 1 :(得分:0)

您可以简单地使用哈希表来跟踪成员:

$seen = @{};
foreach ($Member in $Arrayofmembers)
{
    if($seen[$Member.Name])
    {
        Write-Host "$($Member.Name) is duplicated in group $Group";
    }
    else
    {
        $seen.Add($Member.Name, $true);
    }

    # ... rest of the loop
}