Skip to content

Instantly share code, notes, and snippets.

@lantrix
Forked from JohnLBevan/Test-ADCredential.ps1
Last active September 26, 2018 16:35
Show Gist options
  • Save lantrix/badde2ed9049d6002237a10b0ebc35d3 to your computer and use it in GitHub Desktop.
Save lantrix/badde2ed9049d6002237a10b0ebc35d3 to your computer and use it in GitHub Desktop.
function Test-ADCredential {
<#
.SYNOPSIS
This PowerShell function takes a user name and a password as input and will verify if the combination is correct.
The function returns a boolean based on the result.
.PARAMETER Credential
PS Credential Object.
.EXAMPLE
Test-ADCredential -Credential (Get-Credential)
Returns a True if these credentials work against AD
.LINK
https://gallery.technet.microsoft.com/scriptcenter/Verify-the-Active-021eedea/view/Discussions#content
.INPUTS
PS Credentials Object
.OUTPUTS
Boolean
#>
Param
(
[Parameter(Mandatory,HelpMessage='AD Credentials', ValueFromPipeline)]
[System.Management.Automation.Credential()]
[pscredential]$Credential
)
begin {
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
}
process {
if (!($Credential.UserName) -or !($Credential.GetNetworkCredential().Password)) {
Write-Warning -Message 'Test-ADCredential: Please specify both user name and password'
} else {
if ($Credential.UserName -match '@') {$user = $Credential.UserName.Split("@")[0]}
elseif ($Credential.UserName -match '\\') {$user = $Credential.UserName.Split("\\")[1]}
else {$user = $Credential.UserName}
$DS = [DirectoryServices.AccountManagement.PrincipalContext]::new([DirectoryServices.AccountManagement.ContextType]::Domain)
$DS.ValidateCredentials($user, $Credential.GetNetworkCredential().Password) #NB: Username should not contain domain prefix (i.e. use myUsername instead of myDomain\myUsername)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment