Takes a PSCredential object and validates it against the domain (or local machine, or ADAM instance).
function Test-Credential
{
<#
.SYNOPSIS
Takes a PSCredential object and validates it against the
domain (or local machine, or ADAM instance).
.PARAMETER Credential
A PSCredential object with the username/password you wish to test.
Typically this is generated using the Get-Credential cmdlet.
Accepts pipeline input.
.PARAMETER Context
An optional parameter specifying what type of Credential this is.
Possible values are 'Domain','Machine',and 'ApplicationDirectory.'
The default is 'Domain.'
.OUTPUTS
A boolean, indicating whether the Credentials were successfully validated.
#>
param(
[Parameter(Mandatory, ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
[pscredential]
$Credential,
[Parameter()]
[ValidateSet('Domain', 'Machine', 'ApplicationDirectory')]
[string]
$Context = 'Domain'
)
begin
{
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$DS = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgmentList [System.DirectoryServices.AccountManagement.ContextType]::$Context
}
process
{
$DS.ValidateCredentials($Credential.UserName, $Credential.GetNetworkCredential().Password)
}
}
# ----
# https://gist.github.com/JohnLBevan/8094f45176d2f3b1b830
#http://serverfault.com/questions/276098/check-if-user-password-input-is-valid-in-powershell-script
$cred = Get-Credential #Read credentials
$username = $cred.username
$password = $cred.GetNetworkCredential().password
# Get current domain using logged-on user's credentials
$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName
$domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain, $UserName, $Password)
if ($domain.name -eq $null)
{
Write-Host "Authentication failed - please verify your username and password."
exit #terminate the script.
}
else
{
Write-Host "Successfully authenticated with domain $domain.name"
}