Skip to content

Instantly share code, notes, and snippets.

@evetsleep
Created March 1, 2017 00:07
Show Gist options
  • Save evetsleep/2e2d58f9199d70bda5c66d0d9a9b83de to your computer and use it in GitHub Desktop.
Save evetsleep/2e2d58f9199d70bda5c66d0d9a9b83de to your computer and use it in GitHub Desktop.
New-Credential
function New-Credential{
$counter = 0
$more = $true
while($more){
if($counter -ge 3){
Write-Warning -Message ('Take a deep breath and perhaps a break. You have entered your password {0} times incorrectly' -f $counter)
Write-Warning -Message ('Please wait until {0} to try again to avoid risking locking yourself out.' -f $((Get-Date).AddMinutes(+15).ToShortTimeString()))
Start-Sleep -Seconds 30
}
# Collect the username and password and store in credential object.
$userName = Read-Host -Prompt 'Please enter your domain\username'
$password = Read-Host -AsSecureString -Prompt 'Please enter your password'
try{
$credential = New-Object System.Management.Automation.PSCredential $userName,$password
# Build the current domain
$currentDomain = 'LDAP://{0}' -f $credential.GetNetworkCredential().Domain
# Get the user\password. The GetNetworkCredential only works for the passwrod because the current user
# is the one who entered it. Shouldn't be accessible to anything\one else.
$userName = $credential.GetNetworkCredential().UserName
$password = $credential.GetNetworkCredential().Password
}
catch{
Write-Warning -Message ('There was a problem with what you entered: {0}' -f $_.exception.message)
continue
}
# Do a quick query against the domain to authenticate the user.
$dom = New-Object System.DirectoryServices.DirectoryEntry($currentDomain,$userName,$password)
# If we get a result back with a name property then we're good to go and we can store the credential.
if($dom.name){
Write-Output $credential
$more = $false
Remove-Variable password -Force
}
else{
$counter++
Write-Warning -Message ('The password you entered for {0} was incorrect. Attempts {1}. Please try again.' -f $userName,$counter)
}
}
}
@nlvw
Copy link

nlvw commented Aug 24, 2018

This is great! Only issue is if this is run on a domain that is in a forest it can return true incorrectly. For instance if a 'user1' exists on 'dom1' but not on 'dom2'. The user enters 'dom2\user1' as the user name. Even though user1 does not exist on dom2 this will return as true. This is assuming 'dom1' and 'dom2' are in the same forest.

@Admiral-AI
Copy link

Very well done, thank you for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment