PowerShell script to check user in Active Directory

 Here is a quick PowerShell script to check for user in present in Active Directory.

$user = "JohnDoe"
$searcher =  [ADSISearcher]"(sAMAccountName=$user)"
$results =  $Searcher.FindOne()
If ($results -eq $Null) 

    {"User does not exists"}
Else 

    {"User Exists"}


Same can be done using the user email

$email = "JohnDoe@company.com"
$searcher =  [ADSISearcher]"(mail=$email)"
$results =  $Searcher.FindOne()
If ($results -eq $Null) 

    {"User does not exists"}
Else 

    {"User Exists"}


It can be extended more to retrieve more information on the user. For example if the user account is active in AD.

$email = "JohnDoe@company.com"
$searcher =  [ADSISearcher]"(&(mail=$email)(userAccountControl:1.2.840.113556.1.4.803:=2))"
$results =  $searcher.FindOne()
If ($results -eq $Null) 

    {"User account is enabled"}
Else 

    {"User account is disabled"}


If we want to do this operation in bulk, we can put all the email ids in a text file. Each email id goes to each line as below in the text file.
 
JohnDoe@company.com
BruceWayne@company.com
PeterParker@company.com
...
...

Save the text file and give it some name...say "ADCheckUser.txt". And get our script running as below.

ForEach ($Email in Get-Content "ADCheckUser.txt")
{
    $Searcher =  [ADSISearcher]"(&(mail=$Email)(userAccountControl:1.2.840.113556.1.4.803:=2))"
    $Results =  $Searcher.FindOne()
    If ($Results -eq $Null) 

        {"User account is enabled"}
    Else 

        {"User account is disabled"}
}

Comments

Popular posts from this blog

The all new Movie Central

Movie Central 4.0 (New Release in works)

How to install nVidia Optimus driver