MarcGel
MarcGel

Reputation: 301

PowerShell trying to list users who have group membership similar string

I have a function that helps me grab over 20k users in our AllUsers group (gets ObjectClass,Name,SamAccountname,DistinguishedName). I'm trying to list anyone who has CBA-* groups, but the loop seems to repeat the output a couple of times per user (after the 1st one), when I only want one iteration (many CBA-* possibilities). Here's what I have. Also, I get errors "Get-ADPrincipalGroupMembership : The server was unable to process the request due to an internal error." Any ideas why that would happen? I'm not sure I can see why my code repeats maybe twice, but then seems to move on to the next user just fine?

ForEach ($User in $Users) {

    Get-ADPrincipalGroupMembership -Identity $User.SamAccountName | 
    Select Name | 
    Where-Object {$_.Name -like 'CBA-*'} | 
    ForEach-Object { $User_MemberOf += @($_.Name) } 


  ForEach ($Group in $User_MemberOf) {
        New-Object PSObject -Property @{
            SID = $User.SamAccountName
            Name = $User.name
            Group = $Group 
        }  | Export-Csv -Path $logs -NoTypeInformation -Append       
        }
        }

Upvotes: 0

Views: 313

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

For each loop iteration, you continue to assign values to $User_MemberOf with the addition operator (+=) meaning that for each new user it gets "sanded" more and more with the previous users' memberships.

Two ways to avoid:

Initialize $User_MemberOf as an empty array at the start of each loop iteration:

foreach($User in $Users){
    $User_MemberOf = @()

    Get-ADPrincipalGroupMembership -Identity $User.SamAccountName |Select -Expand Name |Where-Object {
      $_ -like 'CBA-*'
    } |ForEach-Object { 
      $User_MemberOf += $_ 
    }

    foreach($Group in $User_MemberOf){
        # export to CSV
    }
}

Assign output directly from pipeline:

foreach($User in $Users){
    $User_MemberOf = Get-ADPrincipalGroupMembership -Identity $User.SamAccountName |Select -Expand Name |Where-Object {
      $_ -like 'CBA-*'
    } |ForEach-Object { 
      $User_MemberOf += $_ 
    }

    foreach($Group in $User_MemberOf){
        # export to CSV
    }
}

Upvotes: 1

Related Questions