PoshCode Archive  Artifact [5585b1eb36]

Artifact 5585b1eb36db5142922f565aa3c0bcf2b6c5517ad5ede360589fbe13d723c712:

  • File Get-GroupMembership.ps1 — part of check-in [14ba3958d9] at 2018-06-10 12:59:34 on branch trunk — Two cmdlets for and from the Active-Directory uninitiated… (user: Aleksandar size: 1641)

# encoding: ascii
# api: powershell
# title: Get-GroupMembership
# description: Two cmdlets for and from the Active-Directory uninitiated…
# version: 0.1
# type: function
# author: Aleksandar
# license: CC0
# function: Get-DistinguishedName
# x-poshcode-id: 1641
# x-derived-from-id: 1642
# x-archived: 2010-07-18T14:39:31
#
# 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