Friday, March 7, 2014

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: http://1drv.ms/1fSd9PH

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}

PROCESS
{

   $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” }
else
{ $userobject  }

No comments:

Post a Comment

Followers

hit counter