Search code examples
powershellactive-directorydomaincontrollerdirectorysearcher

Specify Active Directory Domain Controller via DirectoryEntry or DirectorySearcher?


I can specify the domain controller when I want to search through AD using this:

$principalContext  = New-Object 'System.DirectoryServices.AccountManagement.PrincipalContext'([System.DirectoryServices.AccountManagement.ContextType]::Domain, $DomainControllerIpAddress, $Container)

How can I specify the domain controller using a DirectoryEntry or DirectorySearcher?


Solution

  • Multiple constructor overloads for the DirectorySearcher take a DirectoryEntry as it's argument, and you can target a specific server when creating one:

    # [adsi] is a type accelerator for the DirectoryEntry class
    $Entry = [adsi]"LDAP://dc01.domain.tld/OU=MyContainer,DC=domain,DC=tld"
    
    # [adsisearcher] is a type accelerator for the DirectorySearcher class
    $Searcher = [adsisearcher]$Entry