I am working with a Powershell script that adds scheduled tasks to systems in our domain. When I run this script, it will prompt me for my password. I sometimes fat finger the password and the process starts, which locks out my account. Is there a way to verify my credentials to make sure that what I typed in will validate with the Domain?

I'd like to find a way to query the Domain controller. I've done some Google searches and I should be able to do a WMI query and trap for an error. I would like to avoid that style of validation if possible.

Any ideas? Thanks in advance.

link|improve this question

80% accept rate
feedback

3 Answers

up vote 4 down vote accepted

I have this in my library:

$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"
}
link|improve this answer
This is exactly what I am looking for. Thanks! – Doltknuckle Jun 3 '11 at 19:50
feedback

This is what I've used in the past; it's supposed to work for local machine accounts and 'application directory', but so far I've only used it successfully with AD credentials:

function Test-Credential {
<#
.SYNOPSIS
    Takes a PSCredential object and validates it against the domain (or local machine, or ADAM instance).

.PARAMETER cred
    A PScredential object with the username/password you wish to test. Typically this is generated using the Get-Credential cmdlet. Accepts pipeline input.

.PARAMETER context
    An optional parameter specifying what type of credential this is. Possible values are 'Domain','Machine',and 'ApplicationDirectory.' The default is 'Domain.'

.OUTPUTS
    A boolean, indicating whether the credentials were successfully validated.

#>
param(
    [parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [System.Management.Automation.PSCredential]$credential,
    [parameter()][validateset('Domain','Machine','ApplicationDirectory')]
    [string]$context = 'Domain'
)
begin {
    Add-Type -assemblyname system.DirectoryServices.accountmanagement
    $DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($context) 
}
process {
    $DS.ValidateCredentials($credential.UserName, $credential.GetNetworkCredential().password)
}

}

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.