Checking if supplied domain user credentials are correct with PowerShell

On a recent project we had the problem of creating multiple Windows Services to be run under a single account. So since we did not want to store the password in source control we had our script prompt us for the password. This worked really well until one day we put the wrong password in, and since Active Directory was set up to lock accounts after three bad tries we found we would instantly lock an account every time we put the password in wrong once.

So the obvious solution was to check once that the credentials you had were right before trying to do all this work and stupidly locking an account.

Of course someone had thankfully asked this question before. And thanks to JimB on ServerFault I basically used his entire answer as it did just what was needed. Original answer on ServerFault.

function Test-Login($serviceUsername, $password){
# http://serverfault.com/questions/276098/check-if-user-password-input-is-valid-in-powershell-script
# Get current domain using logged-on user's credentials
$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName
$domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain, $serviceUsername, $password)

if ($domain.name -eq $null)
{
write-host "Authentication failed - please verify your username and password." -ForegroundColor Red -BackgroundColor Black
return $false;
}
else
{
write-host "Successfully authenticated with domain $serviceUsername" -ForegroundColor Green
return $true;
}
}