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

link|improve this question

33% accept rate
feedback

3 Answers

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

link|improve this answer
feedback

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 }
link|improve this answer
+1 for this one because it uses native powershell cmdlets. – Mark Henderson Mar 16 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 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 at 0:33
feedback

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."}
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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