Search code examples
powershelldsquery

Powershell / dsquery Pull list of users in an array of groups make an array with the unique users


I have been tasked with making sure all admins have the correct permissions. We have a few admin groups so what I though I would do is use powershell and dsquery to pull all the users from these groups and put them in to an array. The user might be in more then one admin groupd so I only want one of each user. I would then use dsget to get more info on all users and output this to a css. Im stuck on the the fact that I cant get -contains to work right. After I have this list of users the reast should be strait forward.

$admingroups = @("Group 1","Group 2","Group 3","Group 4")
$adminnames = @()

foreach ($adming in $admingroups) { 
  $admin = (&dsquery group -samid $adming -limit 0 | dsget group -members -expand)
  if ($adminnames -contains $admin) {
    write-host "Dupes"
  }Else{
    $adminnames += $admin
  }
}

Solution

  • So, you want to see, for each admin user, what admin groups are they in?

    But, your primary question is (correct me if I'm wrong):
    Given that you're retrieving your overall list of admin users by querying each admin group, you may have duplicates, so how do you remove the duplicates?

    In that case the issue is that you're missing a ForEach loop:

    $AdminGroups = @("Group 1","Group 2","Group 3","Group 4")
    $AdminNames = @()
    
    ForEach ($Group in $AdminGroups) {
        $AdminsInGroup = @( dsquery group -samid $Group -limit 0 | dsget group -members -expand )
    
        ForEach( $Admin in $AdminsInGroup ) {
            if( $AdminNames -contains $Admin ) {
                Write-Host "Dupes"
            } else {
                $AdminNames += $Admin
            }
        }
    }
    

    Alternatively, Select-Object has a "-unique" parameter:

    $AdminGroups = @("Group 1","Group 2","Group 3","Group 4")
    $AdminNames = @()
    
    ForEach ($Group in $AdminGroups) {
        $AdminsInGroup = @( dsquery group -samid $Group -limit 0 | dsget group -members -expand )
    
        $AdminNames += $AdminsInGroup
    }
    
    $AdminNames = @( $AdminNames | Select -Unique )