In PowerShell scripts that prompt for a username and password, you sometimes have to validate the entered user credentials before performing any actions. If the user has entered an incorrect login/password, you must determine this and prompt them again.
To test the credentials of the AD user account against the current Active Directory domain, use the following PowerShell function:
$creds=Get-Credential
Function Test-ADCreds {
param($username, $password)
(New-Object DirectoryServices.DirectoryEntry "",$username,$password).psbase.name -ne $null
}
Test-ADCreds -username $creds.UserName -password $creds.GetNetworkCredential().password
Enter the domain username and password (use one of the following formats: username
, domain\username
, or [email protected]
). The script will return True if the user credentials provided are valid.
If the script returns False, the possible causes are
- Invalid username (check that the account exists on a domain) or password
- The user’s account is disabled or locked in the AD
- The domain is not available.
To connect to a domain controller from a computer in a workgroup or another domain, specify an LDAP connection string. Change line 4 of the script as follows:
(New-Object System.DirectoryServices.DirectoryEntry 'LDAP://DC=woshub,DC=loc', $username, $password).psbase.name -ne $null
Or connect to the domain controller using its IP address:
(New-Object System.DirectoryServices.DirectoryEntry 'LDAP://192.168.100.10', $username, $password).psbase.name -ne $null
woshub\username
) or userPrincipalName ([email protected]
) format. In this case, Kerberos authentication is used instead of NTLM.