Validating Active Directory User Account and Password

by May 20, 2013

Ever wanted to check whether a given user account and password was correct? Here is a little function that can help you:

function Test-ADCredential
{
  param(
    [System.Management.Automation.Credential()]
    $Credential
  )

    Add-Type -AssemblyName System.DirectoryServices.AccountManagement 
    $info = $Credential.GetNetworkCredential()
    if ($info.Domain -eq '') { $info.Domain = $env:USERDOMAIN }

    $TypeDomain = [System.DirectoryServices.AccountManagement.ContextType]::Domain
    try
    {
        $pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext $TypeDomain,$info.Domain
        $pc.ValidateCredentials($info.UserName,$info.Password)
    }
    catch
    {
     Write-Warning "Unable to contact domain '$($info.Domain)'. Original error:$_"
    }
}

Simply submit a credential object or a string in the format "domain\username".

Twitter This Tip! ReTweet this Tip!