Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
I needed to locate the LDAP distinguished name of an individual user account in a remote ___domain via PowerShell. Assuming your script is running on a box that is part of a ___domain that has a trust to the remote ___domain we can do this by running a query against Active Directory with LDAP.
By using the DirectorySearcher class we can build complex LDAP queries to find objects in Active Directory. With this information you can do all kinds of fun scripting things.
Here is a sample script:
#Specify the search criteria
$samname="jasonv"
$___domain="dev.lcl"
#Get a list of domains in the forest and grab the DN of the one matching the above parameter.
$forest= [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
$___domain= $forest.Domains | ? {$_.Name -eq$___domain}
$domainDN=$___domain.GetDirectoryEntry().distinguishedName
Write-Output "Found the remote ___domain, the full LDAP distinguished name is $DomainDN"
#Create an LDAP searcher object and pass in the DN of the ___domain we wish to query
$Searcher=New-Object System.DirectoryServices.DirectorySearcher([ADSI]"LDAP://$domainDN")
#Pass in the ceriteria we are searching for.
#In this case we're looking for users with a particular SAM name.
$Searcher.filter="(&(objectCategory=person)(objectClass=user)(sAMAccountName= $samname))"
$results=$Searcher.Findall()
#Loop through the results
Foreach($result in $results){
$User=$result.GetDirectoryEntry()
$userDN=$user.DistinguishedName
Write-Output "Found a user matching with the distingused name of $userDN"
}
Comments
- Anonymous
January 07, 2014
Thanks for sharing this script. Had been trying to figure out how to do this for quite some time.