Photo by regularguy.eth / Unsplash
Test AD authentication with PowerShell

Test AD authentication with PowerShell

Published on 18 Apr 2019

Bastien Perez
Bastien Perez


Test password

Sometimes, it is useful to test Active Directory credentials to validate the login or the password. For example, following the bulk creation of users.

The most commonly used actions is connecting to a remote desktop (RDP) or connecting to a webmail. However, either the number of login to be tested is too important, or no service is accessible to test an authentication.

PowerShell to the rescue

Be careful to NOT test authentication loops with a bad password, otherwise this may lead to AD account lockout.

The script has been tested for NTLM authentication with domain\sAMAccountName. Kerberos authentication has not been tested. These methods may not work for users in the 'Protected Users' group or if NTLM has been disabled.

PowerShell allows you to test login / password authentication against Active Directory using one of these two methods:

$UserName = 'xxxx'
$Password = 'yyyy'

Function Test-ADAuthentication {
    (New-Object DirectoryServices.DirectoryEntry "",$username,$password) -ne $null

Test-ADAuthentication -username $UserName -password $password

or an advanced function if you need to test against another AD domain:

function Test-ADAuthentication {
		[Parameter(Mandatory = $false)]
		[Parameter(Mandatory = $false)]
		[string]$Domain = $env:USERDOMAIN
	Add-Type -AssemblyName System.DirectoryServices.AccountManagement
	$contextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain
	$argumentList = New-Object -TypeName "System.Collections.ArrayList"
	$null = $argumentList.Add($contextType)
	$null = $argumentList.Add($Domain)

	if($null -ne $Server){
	$principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $argumentList -ErrorAction SilentlyContinue

	if ($null -eq $principalContext) {
		Write-Warning "$Domain\$User - AD Authentication failed"
	if ($principalContext.ValidateCredentials($User, $Password)) {
		Write-Host -ForegroundColor green "$Domain\$User - AD Authentication OK"
	else {
		Write-Warning "$Domain\$User - AD Authentication failed"

#Test-ADAuthentication -User toto -Password passXX

#Test-ADAuthentication -User toto -Password passXX -Server

The return values are:

  • TRUE if authentication is successful
  • FALSE if authentication failed. The reason can be:
    • bad login. Test if AD user exists
    • bad password
    • locked out AD acount: Get-ADUser -Identity xxx -Properties LockedOut,AccountLockoutTime | Select samaccountname,LockedOut,AccountLockoutTime
    • disabled AD account: Get-ADUser -Identity xxxx | Select samaccountname,Enabled


banner-Bastien Perez
Bastien Perez

Freelance Microsoft 365 - Active Directory - Modern Workplace