The solution posted here is what I am trying below: Validating PowerShell PSCredentials
My script requires domain credentials to be passed as arguments. Here is how I'm trying to validate the creds:
if ($username -and $pass) {
$Password = ConvertTo-SecureString $pass -AsPlainText -Force
$Credentials = New-Object -Typename System.Management.Automation.PSCredential -ArgumentList $username, $Password
$TestUsername = $Credentials.username
$TestPassword = $Credentials.GetNetworkCredential().password
# Get current domain using logged-on user's credentials
$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName
$domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain,$TestUsername,$TestPassword)
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"
}
}
But for some reason, this always leads me to "Authentication failed - please verify your username and password"
. What is the problem, and would your solution also work from a runas command where creds are not passed in as arguments?