# encoding: ascii
# api: powershell
# title: Get-GroupMembership
# description: Two cmdlets for and from the Active-Directory uninitiated…
# version: 0.1
# type: function
# author: kevinslade
# license: CC0
# function: Get-DistinguishedName
# x-poshcode-id: 3839
# x-archived: 2012-12-28T07:42:39
# x-published: 2012-12-21T07:57:00
#
# Get-DistinguishedName gets you an AD Distinguished name from a user name, and Get-GroupMembership lets you recursively collect a list of all the groups a user is a member of (given that user’s distinguished name). See usage example at the bottom…
#
## Get-DistinguishedName -- look up a DN from a user's (login) name
function Get-DistinguishedName {
Param($UserName)
$ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'')
$ads.filter = "(&(objectClass=Person)(samAccountName=$UserName))"
$s = $ads.FindOne()
return $s.GetDirectoryEntry().DistinguishedName
}
## Get-GroupMembership -- Get AD group membership recursively
function Get-GroupMembership {
Param($DNName,[int]$RecurseLimit=-1)
$groups = ([adsi]"LDAP://$DNName").MemberOf
if ($groups -and $RecurseLimit) {
Foreach ($gr in $groups) {
$groups += @(Get-GroupMembership $gr -RecurseLimit:$($RecurseLimit-1) |
? {$groups -notcontains $_})
}
}
return $groups
}
## Usage:
#################################################################################
## $groups = Get-GroupMembership (Get-DistinguishedName Jaykul)
## # To turn recursion off:
## $groups = Get-GroupMembership (Get-DistinguishedName Jaykul) -RecurseLimit 0