Note: This tip requires PowerShell 2.0 or above.
There are times when you need to validate the credentials of an Active Directory user account. A typical scenario is when you have a service object that no one remembers its credentials and you don’t want to reset it before you make sure you tried all the passwords the object may has.
One option would be to try and log on to the server using those credentials. However, you can’t use that if you want to automate the process. In this case you’d want to check the PrincipalContext.ValidateCredentials method.
The ValidateCredentials method returns a Boolean value that specifies whether the specified username and password are valid. To use that method we first need to load the System.DirectoryServices.AccountManagement assembly (part of .NET 3.5). We create a ContextType object, pass it together with the user domain name to the PrincipalContext object, and then invoke the method.
Add-Type -AssemblyName System.DirectoryServices.AccountManagement $UserName=$env:USERNAME $Password='P@ssword' $Domain = $env:USERDOMAIN $ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain $pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext $ct,$Domain $pc.ValidateCredentials($UserName,$Password)