Powershell: Enumerating a LDAP Group with a large (>1500) number of users

Okay I searched though a lot of PowerShell Blogs for the answer to this but couldn't find a solution that really worked. I finally just took the C# solution from a MSDN article (https://msdn.microsoft.com/en-us/library/ms180907(VS.85).aspx) and converted it to PowerShell. Hopefully this is helpful to someone!

# $LDAPGroup is in the format cn=TestGroup,dc=contoso,dc=com 
$container = 'LDAP://' + $LDAPGroup
$member = 'member'
$counter=0

$GroupEntry = New-Object DirectoryServices.DirectoryEntry($container)
$GroupSearcher = New-Object DirectoryServices.DirectorySearcher($GroupEntry)
$GroupSearcher.Filter="(objectClass=*)"

$rangeStep = 1000
$rangeLow = 0
$rangeHigh = $rangeLow + ($rangeStep - 1)
$lastQuery = $FALSE
$quitLoop = $FALSE

do
{
 if(!$lastQuery)
 {
  $attribRange = 'member;range=' + $rangeLow + '-' + $rangeHigh
 }
 else
 {
  $attribRange = 'member;range=' + $rangeLow + '-*'
 }

 # clear searcher properties and add new range
 # cast to [void] so result won't display

 [void]$GroupSearcher.PropertiesToLoad.Clear()
 [void]$GroupSearcher.PropertiesToLoad.Add($attribRange)

 $Results = $GroupSearcher.FindOne()

 If ($Results -eq $Null)
 {
  write-host " "
  write-host "Error: Unable to find specified LDAP Group" -ForeGroundColor Red;
  write-host " "
  break
 }
 
 foreach($Res in $Results.Properties.PropertyNames)
 {
  # for debugging range
  #write-host "member range: " $Res
 }

 if($Results.Properties.Contains($attribRange))
 {  
  foreach($Res2 in $Results.Properties[$attribRange])
  {
   # cast each member as an ADSI object
   $adsPath = 'LDAP://' + $Res2
   $account=[ADSI]$adspath
   $account.setinfo()
 
   # use PSObject to display the properties of the object

   $obj = New-Object PSObject
 
   $obj | Add-Member -MemberType NoteProperty -Name sAMAccountname -Value $account.properties.samaccountname[0]
   $obj | Add-Member -MemberType NoteProperty -Name DN -Value $account.path
   write $obj
   $counter = $counter + 1

  }
  if($lastQuery)
  {
   $quitLoop = $TRUE
  }
 
 }
 else
 {
  $lastQuery = $TRUE
 }

 if(!$lastQuery)
 {
  $rangeLow = $rangeHigh + 1
  $rangeHigh = $rangeLow + ($rangeStep - 1)
 }

}
until($quitLoop)

write-host " "
write-host "Total users:" $counter

Comments

  • Anonymous
    June 09, 2015
    The comment has been removed