≡ Menu

PowerShell: Search for a user without using AD Module

Active Directory Module is really useful to query Active Directory Domains and forests information. However, it is not possible to get this module installed everywhere because of various reasons. Sometimes it is do with the permissions required for installation and some times is the availability of RSAT binaries etc. So, in such cases, we can query active directory using Native abilities. Let us see how to do that.

To query Active Directory without using PowerShell module, we can use [ADSISearcher] accelerator. It does’t require any special binaries or components. It uses the underlying Directory Services .Net classes which are available by default in any windows system. In below example, I will show you how to search for a user account using CN attribute or SAMACCOUNTNAME.

First we need to prepare the LDAP queries.

Let us say we want to query all users whose CN starts with string “test”. The LDAP query is “(&(ObjectCategory=person)(ObjectClass=user)(cn=test*))”. We can pass this to [ADSISearcher] accelerator, as shown below.

Code:

$search = [adsisearcher]"(&(ObjectCategory=Person)(ObjectClass=User)(cn=test*))"
$users = $search.FindAll()
foreach($user in $users) {
    $CN = $user.Properties['CN']
    $DisplayName = $user.Properties['DisplayName']
    $SamAccountName = $user.Properties['SamAccountName']
    "CN is $CN"
    "Display Name is $DisplayName"
    "SamAccountName is $SamAccountName"
}

Similarly you can find for a specific user by his login name using the LDAP query “(&(ObjectCategory=person)(ObjectClass=user)(samaccountname=testuser1))”. You can update this filter in above code and run it again to get the testuser1 details.

This is just a sample. You can do many more such things with this approach.

Comments on this entry are closed.