This is something that I have recently created so that when a script asks for a credentials and there is an error, it doesn’t display a big, ugly and often intimidating error message for any poor soul trying to run my scripts.
That’s why I have recently (as in yesterday) “created” a “fool proof” way of entering and validating credentials against a domain.
This was a problem because whenever someone ran my script and did ANYTHING other than enter perfectly correct credentials, it would throw and error and exit the script. Or even carry on with the script WITHOUT THE CREDENTIALS, which obviously wouldn’t work. I know, I know. Amateur hour! But it was a crap system I must admit.
That’d why I spent and hour or so creating this beauty! It captures any errors, such as null credentials and incorrect credentials and only continues if a user exists with the same samaccountname as the one entered at the credentials prompt and if the user is in the domain admins group. Just for added “security”. Really I just want the appropriate people to be using the script.
This is the code I use!
#PROMPTING FOR CREDENTIALS $cred = $host.UI.PromptForCredential("Need credentials", "Please enter your username and password.", "", "")
if ($cred -ne $null -and $cred -ne ''){ #CHECKING IF THE CREDENTIAL USERNAME EXISTS $check = $(try {Get-ADUser -Identity $cred.UserName} catch {$null}) if ($check -ne $null){ #GETTING CREDENTIAL USERNAME GROUPMEMBERSHIP $checkadmin = Get-ADPrincipalGroupMembership -Identity $cred.UserName $checkadminrefined = $checkadmin.SamAccountName #PUTTING GROUP MEMBERSHIP INTO AN ARRAY $array = $checkadminrefined #CHECKING IF USER GROUP LIST CONTAINS DOMAIN ADMINS if ($array -contains "Domain Admins"){ Write-Host "Credentials are GOOD! - Continuing with script" -ForegroundColor Green Start-Sleep -Seconds 1 }else{ #RESULT IF USER IS NOT DOMAIN ADMINS Clear-Host Write-Host "Credentials are not a domain admin! - Close and start again" -ForegroundColor Red ; $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") Exit } }else{ #RESULT IF NO USER CAN BE FOUND FROM CREDENTIAL USERNAME Clear-Host Write-Host "Check is empty - No user found matching credentials supplied! - Close and start again" -ForegroundColor Red $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") Exit } }else{ #RESULT IF PROMPT IS CLOSED / NO CREDENTIALS SUPPLIED Clear-Host write-host "No credentials supplied - Close and start again" -ForegroundColor Red $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") Exit }
You should be able to read the script and see which each part does. I left comments in the script which I don’t normally do since it might be easier for you to see what its doing with pointers at each stage.
Enjoy!