PowerShell can easily verify a password against a domain account. In other words, you can bind script logic to passwords maintained in Active Directory.
Here is the code required to send a password to AD and get back a Boolean value: $true if the password is correct, else $false:
# specify user name and user domain
$UserDomain = $env:USERDOMAIN
$UserName = $env:USERNAME
$Password = Read-Host -Prompt "Enter password to test"
# test password
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ContextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$PrincipalContext = [System.DirectoryServices.AccountManagement.PrincipalContext]::new($ContextType, $UserDomain)
Note that this code requires an Active Directory and does not work with local accounts. By default, it uses your current account details. Adjust the $UserDomain, $UserName, and $Password variables accordingly. Note also that ValidateCredentials()checks clear-text string passwords. Be careful and do not store clear-text passwords in scripts. Also, better not ask users to enter passwords as clear text.
Your learning points:
psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU - with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!
ReTweet this Tip!
[System.DirectoryServices.AccountManagement.PrincipalContext]::new($ContextType, $UserDomain)Method invocation failed because [System.DirectoryServices.AccountManagement.PrincipalContext] doesn't contain a method named 'new'.
Correct on the new thing, but the context of this is that target environment is .NET 3.5 and PowerShell V2
So, change it to this Add-Type -AssemblyName System.DirectoryServices.AccountManagement $ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain $pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext $ct,$UserDomain $pc.ValidateCredentials($UserName,$Password)
# Results True
Otherwise use the shorter version in my other response.