#PSTip Validate Active Directory Credentials

Note: This tip requires PowerShell 2.0 or later.

PowerShell let’s you tap into .NET Framework and do all kind of poking. Recently, while reading up this article on CodeProject  came across the ValidateCredentials() method on the PrincipalContext class instance.

Below is how you use this nifty little trick in PowerShell to validate AD creds for a user (One can use this for local machine too):

1
2
3
4
5
6
7
8
# add type to allow validating credentials
Add-Type -AssemblyName System.DirectoryServices.AccountManagement

# Create the Domain Context for authentication
$ContextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain

# We specify Negotiate as the Context option as it takes care of choosing the best authentication mechanism i.e. Kerberos or NTLM (non-domain joined machines).
$ContextOptions = [System.DirectoryServices.AccountManagement.ContextOptions]::Negotiate

Let’s create the instance of the PrinicipalContext class by using one of the Constructor . Note this requires a DC name to be passed. Don’t worry if you don’t know the DC name, we can easily use the $env:USERDNSDOMAIN environment variable and it takes care of it.

1
$PrincipalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($ContextType, $env:USERDNSDOMAIN)

Before it is time to execute the method, let’s see the method definition

1
2
3
4
5
PS> $PrincipalContext.ValidateCredentials
OverloadDefinitions
-------------------
bool ValidateCredentials(string userName, string password)
bool ValidateCredentials(string userName, string password, System.DirectoryServices.AccountManagement.ContextOptions options)

We use the second method definition now to validate the user credential, and we can store the user credentials in a credential object (for ease) here.

1
2
3
PS> $Cred = Get-Credential
PS> $PrincipalContext.ValidateCredentials($cred.UserName, $cred.GetNetworkCredential().password, $ContextOptions)
True

PS># Et Voila !

Share on: