Check existance of domain accounts with Powershell script

Old question, I know, but I feel I need to add this bit here because none of the previous answers use any form of error handling.

Also, if you need to support users from multiple domains, you will have to query the correct domain controller (or query the Global Catalog and specify the DN of a directory partition).

$Domainname = 'ABC'
$Username = 'Administrator'

Try
{
   $DomainController = Get-ADDomainController -DomainName $DomainName -Discover -ErrorAction Stop
   Get-ADUser -Identity $Username -Server $DomainController -ErrorAction Stop

   # user account exists
}
Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]
{
   # no error, user account does not exist
}
Catch
{
   # Domain controller not found, domain unreachable, authentication failure or another error occurred
}

This is what we use to validate accounts. It relies of course on Import-Module ActiveDirectory and either a 2008 R2 DC, or a DC running ADWS:

function validateUser
{
    param(
    [string]$username
    )

    # If the username is passed without domain\
    if(($username.StartsWith("domain\")) -eq $false)
    {
        $user = Get-ADUser -Filter { SamAccountName -eq $username }
        if (!$user)
        {
            return $false
        }
        else
        {
            return $true
        }
    }
    elseif(($username.StartsWith("domain\")) -eq $true)
    {
        $username = ($username.Split("\")[1])
        $user = Get-ADUser -Filter { SamAccountName -eq $username }
        if (!$user)
        {
            return $false
        }
        else
        {
            return $true
        }
    }
}
$userCheck = validateUser -username smith02
if($userCheck -eq $true) { do stuff } else { user doesn't exist }

You can use the Directory Searcher .net object to do this.

Here is a very un-optomized code snippet from one of my utility scripts that has fallen by the wayside.

$AD = [ADSI]"<ldap_connection_string>"
$query = New-Object System.DirectoryServices.DirectorySearcher
$query.SearchRoot = $AD
$Users = $query.FindAll() | Where-Object {$_.properties.objectclass -eq "user"} 

So you should be able to change the .objectclass to .cn or .name and then match against that.

Or don't be lazy like I am and read up on how to construct a proper query :)