Powershell – validate domain user with password

Another common problem yesterday: how to validate a domain user with a password. I had a service account that I suscpected had an invalid password. After some googling and trying different solutions, I came accross a post by Shay Levy that fitted my purpose.

I wrote a function based on the Levy post, and the following function CheckCredentials will validate username on format “domain\user” and password againt the supplied domain.

Add-Type -AssemblyName System.DirectoryServices.AccountManagement 

function CheckCredentials( [String]$username,  [String]$password)
    # find seperator character '\' in username string
    $sepidx = $username.IndexOf('\') ;

    # pick domain from username string
    $domain = $username.Substring(0, $sepidx);
    # pick user from username string
    $user = $username.Substring($sepidx+1, ($username.Length - $sepidx)-1)

    # create instance for domian principle context for input user
    $ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
    $pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext `

    # validate user credential for user with password against domain
    $res = $pc.ValidateCredentials($user,$password)

    return $res; #true: ok, false: invalid username and passwrod

The script will pick the domain from the supplied username string based on the ‘\’ seperator character. The function returns true of the username is successfully validated, otherwise false.