Find a user (or any object) exists in Active Directory

With all Microsoft Active Directory Module for PowerShell, it doesn’t have an cmdlet to simply search a user or group in AD to find it exists or not. Get-ADUser or Get-ADGroup spits an ugly error message if it doesn’t find the object.

I wrote an PowerShell function to do exactly what I wanted. Simple search the given user or group, return True if it exists or return False. If you need it, feel free to use this function.

Download the script here:

# Function: IsUserExists
# Parameter: SamAccountName of the user
# Purpose: Find the user existing in AD or not. Returns True
# if the user exists, or returns False
# Written by Anand Venkatachalapathy
Function IsUserExists()
Param ( $username = “Administrator”)
$strFilter = “(&(objectCategory=User)(SAMAccountName=$username))”

    $objDomain = New-Object System.DirectoryServices.DirectoryEntry

    $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = “Subtree”

    $colProplist = “name”
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}

    $colResults = $objSearcher.FindAll()

    If ($colResults.Count) { Return $true }
Else { Return $false }


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 )

Facebook photo

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

Connecting to %s