PowerShell: Check if credentials are valid

Discovery

When I was trying to configure a scheduled task to use a specific service account the task manager did not want to accept my service account credentials.
I wanted a quick way to find out if the credentials I was using where correct. Some quick browsing on the web lead me to this.

Description

The code requests credentials and checks them with your AD using the DirectoryServices.

$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." -ForegroundColor Red
} else {
    write-host "Successfully authenticated with domain $domain.name" -ForegroundColor Green
}
Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: