AD Search with PowerShell

It is pretty easy to find any object in Active Directory using Active Roles Management Shell from Quest Software . What if you need to run such a search regarding any PowerShell add-ons? A bit of LDAP can help you

1. Create a new searcher object and set some properties

$ADRoot = [ADSI]””
$Searcher = New-Object System.Directoryservices.DirectorySearcher($Root)
$Searcher.SearchRoot = $ADRoot
$Searcher.SearchScope = “subtree”

Note: Use $Searcher.SizeLimit = 2000 if you expect a long list as a result

2. Set a search filter. This is a regular LDAP filter, so you can use a PowerShell variable

$SAMAccountName = “userName”
$Searcher.Filter = “(&(objectCategory=user)(samaccountname=$SAMAccountName))”

or just an LDAP string

$Searcher.Filter = “(&(objectCategory=user)(samaccountname=username))”

3. Run the search. It can be the search for one object

$Result = $Searcher.FindOne()

or for all matching the filter criteria

$Result = $Searcher.FindAll()

4. Get the properties of the AD object

if ($Result -eq $Null)
{Write-Host “— NOT FOUND —“}
$ADobject = $Result.GetDirectoryEntry()
$DN = $ADobject.distinguishedName


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: