Posted in Active Directory, Scripting

PowerShell: Search User Accounts in Active Directory

Active Directory Module has many cmdlets to process many AD related tasks. BUT we don’t have simple search cmdlet.

I had a requirement to check a list of users in AD to see if they exist or not. Get-ADUser doesn’t cut it for my requirement. If a user doesn’t exist, Get-ADUser errors out. So I wrote my own function. It can be used in a script or pipe the user names (SAM Account Name). This function search active directory and returns the AD User object if exists. Otherwise it returns an null value.

Download the script here:

Feel free use it for you purpose.

# Function: Search-User
# Parameter: user’s SAM Account Name
# Description: Search Active Directory with given
# SAM Account Name. Return the AD User object if
# user exists, or return null value
# Written by: Anand Venkatachalapathy
Function Search-User

param([Parameter(ValueFromPipeline)] $User)

BEGIN {import-module activedirectory}


   $filter = “(&(ObjectClass=User)(sAMAccountName=$User))”
   $userobject = Get-ADObject -LDAPFilter $filter

   if ($userobject -eq $null)
        return $null

   return (Get-ADUser $userobject)



To use this function, call the function with a user’s SAM Account Name. E.g.,

$user = “JDoe”
$userobject = Search-User($user)
If ($userobject –eq $null)
{ “$user doesn’t exists in Active Directory” }
{ $userobject  }


Being in Silicon Valley for years, I became a IT Infrastructure Geek by experience and surrounded by other Geeks everywhere. I try to help others by the solutions I found on odd occasions.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s