Powershell function to check if Active Directory users exists

Here is a little powershell function I made to see check if specific active directory users exists or not.

function userExists ([string]$name){
    #written by: √ėyvind Nilsen (oyvindnilsen.com)
    [bool]$ret = $false #return variable
    $domainRoot = [ADSI]''
    $dirSearcher = New-Object System.DirectoryServices.DirectorySearcher($domainRoot)
    $dirSearcher.filter = "(&(objectClass=user)(sAMAccountName=$name))"
    $results = $dirSearcher.findall()

    if ($results.Count -gt 0) { #if a user object is found, that means the user exists.
        $ret = $true

    return $ret

userExists batman

#Example 2:
if(userExists batman) {
   write-host "the user exists"
} else {
   write-host "the user does not exist"
This entry was posted in Scripting and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *