TheGeekery

The Usual Tech Ramblings

PowerShell: Active Directory, and User Groups

Matt Simmons posted a question today on Twitter

Anyone know how to show a user’s group membership in powershell?

The cool thing about PowerShell, like Perl, if it can be done one way, there are probably 10 other ways to achieve the same thing. Here are a couple…

Method 1 – ADSI

1
2
3
4
$user = [ADSI]("CN=Jonathan Angliss,CN=User,DC=local,DC=mydomain,DC=com")
foreach($group in $user.MemberOf) {
  $group
}

This method will show the full DN of each group the user is a member of.

Method 2 – Quest’s Active Directory PowerPack

I’ve been a PowerGUI user for a bit, and the Quest AD PowerPack is pretty damn cool. You don’t have to buy the full product, there is an open source version of PowerGui, but the AD tools are at Quest’s site here. This one is a little easier, as you don’t have to know the full DN for the user, you can search by name, phone, all kinds. Here is a simple example:

1
2
3
4
$user = Get-QADUser -FirstName "Jonathan" -LastName "Angliss"
foreach($group in $user.MemberOf) {
  $group
}

This too returns the full DN for the groups.

Method 3 – Windows 2008 R2 AD Modules

Now there are some requirements behind this one, so go check them out, the least of which is a Windows 2008 R2 server. It’s a little unclear if the R2 box has to be a domain controller or not, but the 2008R2 Active Directory Web Services (ADWS) must be installed on at least one DC.

1
Get-ADPrincipalGroupMembership -Identity "CN=Jonathan Angliss,CN=User,DC=local,DC=mydomain,DC=com"

I cannot validate the syntax exactly on this one, as I don’t have the facilities available to do so.

But there you have it, 3 quick commands to get you access to the user’s groups.

EDIT: I found another one, which uses the ADSI method, but calls up the Directory Services modules…

1
2
3
4
5
6
7
8
9
$searchHandler = New-Object DirectoryServices.DirectorySearcher([ADSI]"")

$searchHandler.filter = "(&(objectClass=user)(sAMAccountName=jonathan.angliss))"

$foundUser = $searchHandler.findOne()

$properties = $foundUser.Properties

$properties.get_Item("memberof")

This one requires a little understanding of LDAP searches, but not too bad otherwise.

Comments