Validating PowerShell PSCredential
I believe using System.DirectoryServices.AccountManagement
is the less ugly way:
This is using ADSI (more ugly?):
$cred = Get-Credential #Read credentials$username = $cred.username$password = $cred.GetNetworkCredential().password# Get current domain using logged-on user's credentials$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName$domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain,$UserName,$Password)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"}
I was having a similar issue with an installer and required to verify the service account details supplied. I wanted to avoid using the AD module in Powershell as I wasn't 100% this would be installed on the machine running the script.
I did the test using the below, it is slightly dirty but it does work.
try{ start-process -Credential $c -FilePath ping -WindowStyle Hidden} catch { write-error $_.Exception.Message break}