Searching in Different Domains

by Oct 23, 2013

When you use the ADSISearcher type accelerator to find Active Directory accounts, it defaults to the current domain you are logged on to. If you need to find an account in a different domain, make sure you define the search root accordingly.

This example will find all accounts with a SamAccountName that starts with "tobias", and it searches the domain "powershell.local" (adjust to a real domain name, of course):

# get all users with a SamAccountName that starts with "tobias"
$searcher = [ADSISearcher]"(&(objectClass=User)(objectCategory=person)(sAMAccountName=tobias*))"

# use powershell.local for searching
$domain = New-Object System.DirectoryServices.DirectoryEntry('DC=powershell,DC=local')
$searcher.SearchRoot = $domain

# execute the query
$searcher.FindAll() 

Twitter This Tip! ReTweet this Tip!