Search code examples
powershellactive-directorydsquery

Determining if a given user is in a given global group


I’m trying to search through Active Directory using the AD module in PowerShell. I’m trying to determine whether a given user is in a given global group. The issue is that I’m using -match meaning if there is a username that contains another within it, such as 'smith_pl' containing 'smith_p'. The user 'smith_p' will be shown to be in the group.

So my question is: Is there a better way of getting a $True or $False return depending if a user is in a giving global group using the AD module?

If not

Is there a way of getting the output from $ListOfmembers into an array so I can use -eq instead of -match?


Part of Script:

$ListOfmembers = dsquery group domainroot -name $globalgroup | 
                 dsget group -members | 
                 dsget user -samid -L

$checkMember = $False
#Search if the user is in output the list
If($ListOfmembers -match $Logonname){
    $checkMember = $True
}

ListOfmembers Output:

samid: user05_t

samid: user23_s

samid: Admin

samid: user45_s

dsget succeeded

Any help would be appreciated, Cheers.


Solution

  • You can do it like this:

    [reflection.assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement")
    $username = "samaccountname"
    $ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
    $user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ct, $username)
    $g =  $user.GetGroups()
    ( $g | select -expa name ) -contains 'groupname'