Validate the existence of user account in AD using Powershell

This is a small script that is used to check if the given user account does exists in Active Directory. If you have a xml/csv/txt file with multiple user accounts to be checked then this script can be used with some modification to read the data from the file.

The input data for the below script are:

  • Username: This variable will hold the user account to be checked
  • ADServer: Active Directory server name to which the LDAP query will be sent
  • ADPort: Active Directory port number. Port 389 is the default port for the Lightweight Directory Access Protocol

Below is the script.

######################################################################################################
#Validate if the specified account exists in AD
######################################################################################################

#ActiveDirectory Module is been imported to Powershell. This is explained here.
Import-Module ActiveDirectory

$Username=Read-host -prompt "`nPlease enter the user account [domain\account]:"
$ADServer=Read-host -prompt "`nPlease enter the AD Server name [NetBIOS name]:"
$ADPort=Read-host -prompt "`nPlease enter the AD port no.:"

#Using WMI object to retrieve the domain name
$ADDomainName=(Get-WmiObject Win32_ComputerSystem).Domain

#Splitting the domain name a.com to a and com
$D1name=($ADDomainName.Split(".")[0])
$D2name=($ADDomainName.Split(".")[1])
write-host("Retrieved the Root AD domain.")

#Function with LDAP query to check the user account in AD
Function Check-ADUser
{
    Param ($Username)
 
    $Username = ($Username.Split("\")[1])
    $ADCompletePath = "LDAP://"+$ADServer+":"+$ADPort+"/DC="+$D1name+",DC="+$D2name
    $ADRoot =  [ADSI]'"$ADCompletePath"'

    $ADSearch = New-Object System.DirectoryServices.DirectorySearcher($ADRoot)  
    $SAMAccountName = "$Username"
    $ADSearch.Filter = "(&(objectClass=user)(sAMAccountName=$SAMAccountName))"
    $Result = $ADSearch.FindAll()
 
    If($Result.Count -eq 0)
    {
        $Status = "0"
    }
    Else
    {
        $Status = "1"
    }
     
    $Results = New-Object Psobject
    $Results | Add-Member Noteproperty Status $Status
    Write-Output $Results     
}

$Status = (Check-ADUser -username $username).Status
If ($Status -eq 1)
{
    write-host("$UserName exists.")
} Else {
    write-host("$UserName does not exists. Please give a valid account.")
    Exit
}