Current Version:
function setAutoLogon($username,$password){
$regWinlogon='REGISTRY::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
$regKeyUsername='DefaultUserName'
$regKeyPassword='DefaultPassword'
$kegKeyAutologin='AutoAdminLogon'
$regKeyDefaultDomain='DefaultDomain'
function testCredential($username,$password){
# Get current domain using logged-on user's credentials
$isDomainJoined=$env:USERDOMAIN -ne $env:COMPUTERNAME
if($isDomainJoined){
$domain="LDAP://"+([ADSI]"").distinguishedName # Legacy method without importing ActiveDirectory module
$login=New-Object System.DirectoryServices.DirectoryEntry($domain,$username,$password)
try{
if($null -ne $login.name) {
write-host "$username credential is valid" -foregroundcolor green
return $true
}else{
write-warning "invalid credentials"
return $false
}
}catch{
write-warning $_
return $false
}
}else{
if(!(get-command psexec.exe)){
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
if (!(Get-Command choco.exe -ErrorAction SilentlyContinue)) {
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
}
$null=choco install sysinternals -y
}
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "psexec.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "\\$env:computername -u $username -p $password -s cmd /c hostname"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
if($p.ExitCode -eq 0){
return $true
}else{
return $false
}
}
}
$isDomainJoined=$env:USERDOMAIN -ne $env:COMPUTERNAME
$isPasswordValid=testCredential $username $password
if($isPasswordValid){
Set-ItemProperty -Path $regWinlogon -Name $regKeyUsername -Value $username
Set-ItemProperty -Path $regWinlogon -Name $regKeyPassword -Value $password
Set-ItemProperty -Path $regWinlogon -Name $kegKeyAutologin -Value 1
if($isDomainJoined){
Set-ItemProperty -Path $regWinlogon -Name $regKeyDefaultDomain -Value $env:USERDOMAIN
}
write-host "$env:computername has been set for auto-logon with account $username" -ForegroundColor Green
write-host "Please reboot for changes to take effect."
}else{
write-warning "Provided password is invalid for account $username"
}
}
Old batch commands:
# set /p password="Enter password for %USERNAME%: "
# reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultUserName /t REG_SZ /d %USERNAME% /f
# reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultPassword /t REG_SZ /d %password% /f
# reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AutoAdminLogon /t REG_SZ /d 1 /f
Categories: