$distinguishedName = "CN=Doe\, John,OU=Advertising,OU=User,OU=New York,OU=Accounts,DC=usa,DC=corp,DC=foobar,DC=local" $objectDomain = ((($distinguishedName -replace "(.*?)DC=(.*)",'$2') -replace "DC=","") -replace ",",".") # Get a local domain controller $localDomainController = ([System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite()).Servers | Where-Object { $_.Domain.Name -eq $objectDomain } | ForEach-Object { $_.Name } | Select-Object -first 1 $userObject = [ADSI]"LDAP://$localDomainController/$distinguishedName" Write-Host $userObject.mail
Friday, January 21, 2011
Return a Local Domain Controller in the Current Site for a Specific Domain
Below is a good one liner to return a local Domain Controller for a specific domain in the current site of the computer running a PowerShell script. In the example script, we are taking a known distinguished name, obtaining the domain it resides using code from this post, using that domain information to obtain a local domain controller in the current site using the one liner and finally obtaining the user object from Active Directory so we can output attributes -- in this case, an e-mail address. This script assumes that you have one valid domain controller for the specific domain in the current site. In a multi-domain forest, the security context you execute a PowerShell script will not always be in the same domain as the object you are interested. This can cause LDAP queries to fail (unless you are using chase referrals which are slow) and it is not always suitable to use a Global Catalog query as the attributes you are interested in may not be in the Partial Attribute Set.
Labels:
Active Directory,
PowerShell
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment