PowerTip: Use PowerShell to Find if User Is Nested Group Member

Doctor Scripto

Summary: Use Windows PowerShell to find if a user is a nested member of a particular group. Hey, Scripting Guy! Question How can I use Windows PowerShell to quickly find if a user is a nested member of a particular group,
           for example, Domain Admins?

Hey, Scripting Guy! Answer Use the -RecursiveMatch LDAP filter operator:

Get-ADUser -Filter ‘memberOf ‑RecursiveMatch “CN=Administrators,CN=Builtin,DC=Fabrikam,DC=com”‘ ‑SearchBase “CN=Administrator,CN=Users,DC=Fabrikam,DC=com”

If the user is a member of the group, the query returns an AD object representing the user.
If not a member of the group, the query returns nothing.

You can even use it in a function:

Function Test-ADGroupMember {

Param ($User,$Group)

  Trap {Return “error”}

  If (

    Get-ADUser `

      -Filter “memberOf -RecursiveMatch ‘$((Get-ADGroup $Group).DistinguishedName)'” `

      -SearchBase $((Get-ADUser $User).DistinguishedName)

    ) {$true}

    Else {$false}

}

Now we have a simple function to check if a user is nested into a privileged group:

PS C:> Test-ADGroupMember -User Guest -Group “Domain Admins”

True

PS C:> Test-ADGroupMember -User JoeJrAdmin -Group “Domain Admins”

False

PS C:> Test-ADGroupMember -User bogus -Group “Domain Admins”

error  

0 comments

Discussion is closed.

Feedback usabilla icon