Search LDAP Entries using Powershell

Below little script shows how to connect to Active Directory / LDAP and search for entries.


$mySearcher = New-Object System.DirectoryServices.DirectorySearcher

# it is possible to specify manually a ldap search Path:
#$mySearcher.SearchRoot = "LDAP://DC=de,DC=myComapny,DC=com"

# or to get current ldap path (for example: DC=de,DC=myComapny,DC=com)
$objDomain = New-Object System.DirectoryServices.DirectoryEntry

$mySearcher.SearchRoot = $objDomain

# search for object class "user" with attribte "name=TestUser1"
$mySearcher.Filter = "(& (objectClass=user) (name=TestUser1))"
$mySearcher.SearchScope = "sub"
$mySearcher.PageSize = 10

# specifiy the attributes you would like to retrieve
$myAttributes = ("telephonenumber", "mail", "department")
# comment below line to get all attributes

$abc = $mySearcher.FindAll()

# show all attributes and values
foreach ($i in $abc.Properties.PropertyNames){
    Write-Host $i , "=" , $abc.Properties.$i

The Script will generate the following output:

mail =
telephonenumber = +49XXXXXXXX
department = MyDepartment
adspath = LDAP://<removed_by_author>