0

i have the following code:

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

which works perfectly but i want to list all duplicates in the $Record."Name" = $Member.name with specific group so for example:

username=barry is duplicated in GROUP XYZ

i tried already the following:

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

}
}
1
  • 3
    Please include minimal reproducible example, not full code in your question. It'd be far more readable for people trying to answer. Commented Jun 7, 2019 at 13:37

2 Answers 2

11

The simplest answer is to just pipe $Table to Group-Object and filter for groups with a count greater than one at the end as such:

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

If you are looking to do this in the middle of your loop you could do so by grouping the results of Get-ADGroupMember, but I think it'll probably be faster to do it all at the end.

Sign up to request clarification or add additional context in comments.

Comments

2

You could simply keep track of the members using a hashtable:

$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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.