Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

Is there a Powershell cmdlet or script to query Active Directory if a given domain account (such as "myDomain\myUser") exists?

share|improve this question

3 Answers 3

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 }
share|improve this answer
    
+1 for this one because it uses native powershell cmdlets. –  Mark Henderson Mar 16 '12 at 20:17
    
My inbox seems to show a little bit more of your reply; something about streamlining it. If you still want to, please feel free to do so! –  Robin Mar 17 '12 at 0:21
    
Hey robin. I did originally write that but then I realized i didn't quite have time to do it. Maybe tomorrow... –  Mark Henderson Mar 17 '12 at 0:33

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 :)

share|improve this answer

I would grab the Quest AD Roles cmdlets - http://www.quest.com/powershell/activeroles-server.aspx - and user their Get-QADUser cmdlet with the -Identity parameter.

For example,

$username = "mydomain\myusername"

if (Get-QADUser -Identity $username)
{Write-Host "It's alive"}
else
{Write-Host "Account does not exist."}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.