We prompt for credentials in many of our scripts. Have you ever wondered if the entered credentials is right or wrong? It is always good idea to verify that entered credentials is correct before proceeding with further execution of the script.
The function discussed in this article will provide a easy way to verify if the entered credentials are valid or not. This function uses classes and methods in System.DirectoryServices.AccountManagement name space, especially ValidateCredentials method.
The Test-ADCredential function takes PSCredential argument as input. This is optional one. If you don’t specify it, a prompt will appear for you enter the credentials. That means we can use this function in our scripts as well as for adhoc testing needs.
Code
function Test-ADCrential{ [CmdletBinding()] param( [pscredential]$Credential ) try { Add-Type -AssemblyName System.DirectoryServices.AccountManagement if(!$Credential) { $Credential = Get-Credential -EA Stop } if($Credential.username.split("\").count -ne 2) { throw "You haven't entered credentials in DOMAIN\USERNAME format. Given value : $($Credential.Username)" } $DomainName = $Credential.username.Split("\")[0] $UserName = $Credential.username.Split("\")[1] $Password = $Credential.GetNetworkCredential().Password $PC = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Domain, $DomainName) if($PC.ValidateCredentials($UserName,$Password)) { Write-Verbose "Credential validation successful for $($Credential.Username)" return $True } else { throw "Credential validation failed for $($Credential.Username)" } } catch { Write-Verbose "Error occurred while performing credential validation. $_" return $False } }
Output
Run the function without arguments and it will prompt you to enter credentials
Test-ADCredential
Run the function by passing credential object as argument and it will return the output straightway.
$myCreds = Get-Credential Test-ADCredential -Credential $Mycreds
Do you have any questions about how this function works? Please write in the comments section, we will get back on that.
Comments on this entry are closed.
I like that solution!. Simple and useful