次の方法で共有


Searching across active directory domains in PowerShell

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.