Accessing Non-Microsoft LDAP Servers

by Mar 30, 2015

All Versions

There are free Active Directory cmdlets from Microsoft (part of the RSAT tools) and Dell (Quest). They take the complexity out of accessing a domain controller, and ask for information.

To access a non-Microsoft LDAP server, while there are no ready to use cmdlets, you can use the .NET Framework functionality.

Here is some sample code that illustrates how you contact such an LDAP server, submit an LDAP query, and retrieve the results.

The script assumes the LDAP server at 192.168.1.1 and port 389, as part of the domain “mycompany.com”, with a group named “SomeGroup”. It then lists the user accounts that are members of that group:

$LDAPDirectoryService = '192.168.1.1:389'
$DomainDN = 'dc=mycompany,dc=com'
$LDAPFilter = '(&(cn=SomeGroup))'


$null = [System.Reflection.Assembly]::LoadWithPartialName('System.DirectoryServices.Protocols')
$null = [System.Reflection.Assembly]::LoadWithPartialName('System.Net')
$LDAPServer = New-Object System.DirectoryServices.Protocols.LdapConnection $LDAPDirectoryService
$LDAPServer.AuthType = [System.DirectoryServices.Protocols.AuthType]::Anonymous

$LDAPServer.SessionOptions.ProtocolVersion = 3
$LDAPServer.SessionOptions.SecureSocketLayer =$false
 
$Scope = [System.DirectoryServices.Protocols.SearchScope]::Subtree
$AttributeList = @('*')

$SearchRequest = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $DomainDN,$LDAPFilter,$Scope,$AttributeList

$groups = $LDAPServer.SendRequest($SearchRequest)

foreach ($group in $groups.Entries) 
{
  $users=$group.attributes['memberUid'].GetValues('string')
  foreach ($user in $users) {
    Write-Host $user
  }
}

Twitter This Tip! ReTweet this Tip!