-
-
Save lantrix/badde2ed9049d6002237a10b0ebc35d3 to your computer and use it in GitHub Desktop.
Script to test AD credentials; heavily based on https://gallery.technet.microsoft.com/scriptcenter/Verify-the-Active-021eedea/view/Discussions#content
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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