PowerShell to enable and disable the Windows autologon with an automatic generated password.

 In the automation, we have is often the case that an interactive desktop is required. This can be achieved with an autologon. Here is a PowerShell script for automating this function.

 

Parameter:

LogonCount = number of automatic logins
AutostartScript = Optonal a batch that runs after automatic logon
RunOnceautostartScript = Optional: a batch run once after logon
Admin = $ true or $ false - should the local account get admin rights?

 <#

  Andreas Nick' 2017

.SYNOPSIS
   Enable and disable autologon with automatic generated password
.PARAM
   LogonCount - number of automatic logins
.PARAM 
   AutostartScript = Optonal a batch that runs after automatic logon
.PARAM
  RunOnceautostartScript = Optional: a batch run once after logon
.PARAM
  Admin = $ true or $ false - should the local account get admin rights?   

.DESCRIPTION
   This script is used for automatic Installations with a Reboot (for example)
#>




Function Enable-Autologon{
Param(
     [Parameter(Mandatory=$False )]
     [String] $LogonCount,
     [Parameter(Mandatory=$False)]
     [string] $AutostartScript,
     [Parameter(Mandatory=$False)]
     [string] $RunOnceautostartScript,
     [Parameter(Mandatory=$False )]
     [Switch] $Admin=$true
     )

     $AutoLogonUser = "AutoLogonUser"
     $Autologon = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
     $RunKey = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run"
     $RunOnce= "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce\";

     #DeleteAutologonUser if exist    
     Get-LocalUser -Name $AutoLogonUser -ErrorAction SilentlyContinue | Remove-LocalUser

     #Create Autostart Useraccount
     [String] $Password = 'A'+ $(Get-Random -Maximum 9999999999999 -Minimum 1000000000000)
     [String] $Password+='$1'
     $SecPwd = ConvertTo-SecureString $Password -AsPlainText -Force
     New-LocalUser $AutoLogonUser -FullName $AutoLogonUser -Password $SecPwd 

     # Add to Administrtors 
     if ($admin){
         Add-LocalGroupMember -Name (Get-LocalGroup administ*).Name -Member $AutoLogonUser
     }

     #Enable Autologin
     If( $LogonCount){ Set-ItemProperty $Autologon "AutoLogonCount" -Value "$LogonCount" -type dword -Force } else {
         Set-ItemProperty $Autologon "AutoLogonCount" -Value "1" -type dword
     }

     #RunKey Script
     if($autostartScript){ Set-ItemProperty $RunKey "(Default)" -Value "$autostartScript" -type string }

     #RunOnceKey
     if($RunOnceautostartScript){ Set-ItemProperty $RunOnce "(Default)" -Value "$RunOnceautostartScript" -type string -Force }

     #Enable Autologon
     Set-ItemProperty $Autologon "AutoAdminLogon" -Value "1" -Type string
     Set-ItemProperty $Autologon "DefaultUsername" -Value $($env:COMPUTERNAME+'\'+$AutoLogonUser) -Type string
     Set-ItemProperty $Autologon "DefaultPassword" -Value $Password -Type string
}


#Enable-Autologon -LogonCount 1