Validating User Account Passwords (Part 1)

by Aug 10, 2020

PowerShell can test user account passwords for you. This works both for local and domain accounts. Here is a sample function called Test-Password:

function Test-Password
{
   param
   (
      [Parameter(Mandatory)]
      [string]
      $Domain,

      [Parameter(Mandatory)]
      [string]
      $Username,

      [Parameter(Mandatory)]
      [string]
      $Password

   )

   # load assembly for required system commands
   Add-Type -AssemblyName System.DirectoryServices.AccountManagement 


   # is this a local user account?
   $local = $Domain -eq $env:COMPUTERNAME

   if ($local)
   {
      $context = [System.DirectoryServices.AccountManagement.ContextType]::Machine
   }
   else
   {
      $context = [System.DirectoryServices.AccountManagement.ContextType]::Domain
   }
   # test password
   $PrincipalContext = [System.DirectoryServices.AccountManagement.PrincipalContext]::new($context, $Domain)
   $PrincipalContext.ValidateCredentials($UserName,$Password)
}

It requires the domain name (or local machine name), a user name, and the password. The function returns $true when the password is correct.

Note that the system method used here requires a clear-text password. Entering clear-text passwords is not safe, so in our next tip we improve the function to prompt the password in a masked way.


Twitter This Tip! ReTweet this Tip!