Skip to content

Instantly share code, notes, and snippets.

@ScriptingPro
Created January 4, 2018 22:33
Show Gist options
  • Save ScriptingPro/b294ff7f0baf47d304649e162f9d2dce to your computer and use it in GitHub Desktop.
Save ScriptingPro/b294ff7f0baf47d304649e162f9d2dce to your computer and use it in GitHub Desktop.
LDAP bind to server/port with PowerShell using DirectoryEntry Class and query with DirectorySearcher Class
# define your query filter
$LDAPfilter = "(samaccountname=*)"
# define the object attributes you want returned
$Attributes = @"
samaccountname
givenname
surname
mail
"@ -split [System.Environment]::NewLine
# if you want to specify port#, then your LDAP string will need to look like this..
$LDAPPath = "LDAP://mydomain.com:3268/DC=mydomain,DC=com"
# define userid and pass
$BindUser = "myuserid"
# although this will work, you will want to use other methods so that you're not storing your password in the script
$BindPass = "mypassword"
# more on authentication types: https://msdn.microsoft.com/en-us/library/system.directoryservices.authenticationtypes(v=vs.110).aspx
$AuthType = [System.DirectoryServices.AuthenticationTypes]::ServerBind
# more on DirectoryEntry: https://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry(v=vs.110).aspx
$DirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry($LDAPPath,$BindUser,$BindPass)
# more on DirectorySearcher: https://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher(v=vs.110).aspx
$DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher($DirectoryEntry,$LDAPfilter)
$Attributes | %{$DirectorySearcher.PropertiesToLoad.Add($_)} | Out-Null
# now we're ready to execute
$results = $directorySearcher.FindAll()
# and here's what we have
$results
$results.Properties
$results.properties["samaccountname"]
# now let's say i wanted to get the entire entry for the first user
$thisuser = $results[0].GetDirectoryEntry()
# now i can get whatever i want on this entry...
$thisuser.properties["proxyAddresses"]
$thisuser.properties["msExchMailboxSecurityDescriptor"]
# get all the propertynames
$thisuser.properties.propertynames
# look at what's in each
$thisuser.properties.propertynames | select @{n="attr";e={$_}}, @{n="value";e={$($thisuser.properties["$_"] | Out-String).trim()}}
# there's other ways.. i'll have to look
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment