Find a user in your AD


posted by Tobias Weltner
11-15-2008

Downloads: 688
File size: 306 B
Views: 3,162

Embed
Find a user in your AD
  1. function Get-User ($UserName)  
  2.   $searcher = new-object DirectoryServices.DirectorySearcher([ADSI]""
  3.   $searcher.filter = "(&(objectClass=user)(sAMAccountName= $UserName))" 
  4.   $Searcher.CacheResults = $true 
  5.   $Searcher.SearchScope = �Subtree� 
  6.   $Searcher.PageSize = 1000 
  7.   $searcher.findall() 
simple script defines a function called Get-User which accepts a username or part of it with wildcards. It returns all users that fit your query. This code does not rely on 3rd party stuff. You can easily expand it to query for anything. Simply replace the filter expression with the filter you want. HINT: use the Microsoft MMC Active Directories Computer and Users, then create a custom query. Once done, you will see a query string. You can copy and paste that query string into this script to get the search results you need.

Comments

p3dr0 wrote re: Find a user in your AD
on 04-03-2009 5:39 AM

objectclass=user doesn't work good because in my Active Directory computers have this five entries:

>>> objectClass: top; person; organizationalPerson; user; computer;  <<<

So this script lists also computer accounts. better filter property is  objectcategory=person

good luck

Aleksandar wrote re: Find a user in your AD
on 04-03-2009 2:00 PM

So, the proper filter will look like this:

$searcher.filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=$UserName))"

Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.