Check user credentials and set auto logon

I had several requests from the developers at our company, to enable auto logon for various servers. I knew this was possible through regedit (as explained in this Microsoft support article)

Though, sometimes it needed to be done on (test) servers which reside on a domain and sometimes it needed to be done one (stand-alone) azure servers. Thus I wanted to automate this process.

I need to be able to validate the credentials first. Also I needed to know if a computer is part of a domain. It seems that if the logged on user is a domain account, the environment variable USERDNSDOMAIN is present. In my case this check is enough to determine if a computer is part of a domain or not (as all accounts that are logged on in domain joined computers are domain account, and in cases they are local account, I would want to set the auto logon for that local account).

Thus it is east to check if the computer is part of a domain or not. I just check if $env:USERDNSDOMAIN equals to $null.

Then I’ll do an extra check if $env:COMPUTERNAME equals $env:USERDOMAIN. If so, the computer is definitely not domain joined.

Then I can check the user credentials that were supplied with the Get-Credential command.

Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$Obj = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('machine', $Computer)
If($Obj.ValidateCredentials($Username, $Password) -eq "True")

If the computer is part of a domain, I’ll have the check the credentials with the DC. This can be achieved with this command:

$CurrentDomain = "LDAP://" + ([ADSI]"").distinguishedName
$Domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain,$UserName,$Password)

If the $Domain variable is $null, the supplied credentials don’t work. Otherwise they are correct and the $Domain variable will contain the LDAP path to the domain, the distinguishedName (and other domain related information).

So if the account is verified, in both cases I can set the registry keys

$RegKeyPathWinLogon = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
Set-ItemProperty -Path $RegKeyPathWinLogon -Name "AutoAdminLogon" -Value "1"
Set-ItemProperty -Path $RegKeyPathWinLogon -Name "DefaultUserName" -Value "$Username"
Set-ItemProperty -Path $RegKeyPathWinLogon -Name "DefaultPassword" -Value "$Password"

You can download the entire script here.

Tags: , , ,

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: