November 25th, 2014

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

Doctor Scripto
Scripter

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  

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.