Menu
CCMEXEC.COM – Enterprise Mobility
  • Home
  • General
  • Configuration Manager
  • Windows 10
  • Windows 11
  • Intune
  • GitHub
  • About
CCMEXEC.COM – Enterprise Mobility

Windows 10 Secure AutoLogon – PowerShell

Posted on August 17, 2020August 17, 2020 by Jörgen Nilsson

I wrote a blog post in June on how to use AutoLogon.exe in a Task Sequence to configure AutoLogon in Windows 10. https://ccmexec.com/2020/06/configuring-autologon-during-osd-using-autologon-exe/

After writing that post my colleague Johan Schrewelius wrote a nice little C# part for us which we use in Powershell so we can create and configure a LSA secret using PowerShell instead of using Autologon.exe. Which doesn’t store the password in clear-text in the registry as it with traditional solutions.
The script also creates a Schedule Task without any filecopying needed, a clean and nice solution. As background the OOBE part of the Windows setup clears out all the AutoLogon registry keys which is one of the reasons to use a Schedule Task that configures Autologon after deployment.

The script does the following:
1. Create a Schedule Task that runs the PowerShell script after the first reboot.
2. The script configures the necessary registry keys for Autologon and a LSA secret with the password so it is not stored in clear-text.
3. Deletes the Schedule Task
4. Reboots the computer so it logs on automatically.

The script will use the following three variables as shown below to configure AutoLogon.
They can either be configured using Device variables, Collection variables, Task Sequence variables or script.

Example Collection variables used for Autologon

in the Task Sequence I use the following three steps. One that moves the computer to a Kiosk OU to make sure the correct Group Policies are applied.
And the Reboot after OSD step sets the “SMSTSPostAction” variable to “cmd /c shutdown /r /t 30 /f”.

Sample Task Sequence Kiosk group

The PowerShell script itself can be imported in the Task Sequence instead of using a Package.

Sample Configure AutoLogon step
AutoLogon PowerShell script imported

The script itself, it can also be downloaded from the Github repository: https://github.com/Ccmexec/MEMCM-OSD-Scripts/tree/master/Kiosk%20scripts

<#
    Name: Autologon.ps1 
    Version: 1.0
    Author: Johan Schrewelius
    Date: 2020-06-15
#>

$tsenv = New-Object -COMObject Microsoft.SMS.TSEnvironment

[string]$Username = $tsenv.Value("KIOSKUSER")
[string]$Domain = $tsenv.Value("KIOSKDOMAIN")
[string]$Password = $tsenv.Value("KIOSKPASSWORD")

$Code = @'
Add-Type @"
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
 
namespace PInvoke.LSAUtil {
    public class LSAutil {
        [StructLayout (LayoutKind.Sequential)]
        private struct LSA_UNICODE_STRING {
            public UInt16 Length;
            public UInt16 MaximumLength;
            public IntPtr Buffer;
        }
 
        [StructLayout (LayoutKind.Sequential)]
        private struct LSA_OBJECT_ATTRIBUTES {
            public int Length;
            public IntPtr RootDirectory;
            public LSA_UNICODE_STRING ObjectName;
            public uint Attributes;
            public IntPtr SecurityDescriptor;
            public IntPtr SecurityQualityOfService;
        }
 
        private enum LSA_AccessPolicy : long {
            POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L,
            POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L,
            POLICY_GET_PRIVATE_INFORMATION = 0x00000004L,
            POLICY_TRUST_ADMIN = 0x00000008L,
            POLICY_CREATE_ACCOUNT = 0x00000010L,
            POLICY_CREATE_SECRET = 0x00000020L,
            POLICY_CREATE_PRIVILEGE = 0x00000040L,
            POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L,
            POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L,
            POLICY_AUDIT_LOG_ADMIN = 0x00000200L,
            POLICY_SERVER_ADMIN = 0x00000400L,
            POLICY_LOOKUP_NAMES = 0x00000800L,
            POLICY_NOTIFICATION = 0x00001000L
        }
 
        [DllImport ("advapi32.dll", SetLastError = true, PreserveSig = true)]
        private static extern uint LsaStorePrivateData (
            IntPtr policyHandle,
            ref LSA_UNICODE_STRING KeyName,
            ref LSA_UNICODE_STRING PrivateData
        );
 
        [DllImport ("advapi32.dll", SetLastError = true, PreserveSig = true)]
        private static extern uint LsaOpenPolicy (
            ref LSA_UNICODE_STRING SystemName,
            ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
            uint DesiredAccess,
            out IntPtr PolicyHandle
        );
 
        [DllImport ("advapi32.dll", SetLastError = true, PreserveSig = true)]
        private static extern uint LsaNtStatusToWinError (
            uint status
        );
 
        [DllImport ("advapi32.dll", SetLastError = true, PreserveSig = true)]
        private static extern uint LsaClose (
            IntPtr policyHandle
        );
 
        [DllImport ("advapi32.dll", SetLastError = true, PreserveSig = true)]
        private static extern uint LsaFreeMemory (
            IntPtr buffer
        );
 
        private LSA_OBJECT_ATTRIBUTES objectAttributes;
        private LSA_UNICODE_STRING localsystem;
        private LSA_UNICODE_STRING secretName;
 
        public LSAutil (string key) {
            if (key.Length == 0) {
                throw new Exception ("Key lenght zero");
            }
 
            objectAttributes = new LSA_OBJECT_ATTRIBUTES ();
            objectAttributes.Length = 0;
            objectAttributes.RootDirectory = IntPtr.Zero;
            objectAttributes.Attributes = 0;
            objectAttributes.SecurityDescriptor = IntPtr.Zero;
            objectAttributes.SecurityQualityOfService = IntPtr.Zero;
 
            localsystem = new LSA_UNICODE_STRING ();
            localsystem.Buffer = IntPtr.Zero;
            localsystem.Length = 0;
            localsystem.MaximumLength = 0;
 
            secretName = new LSA_UNICODE_STRING ();
            secretName.Buffer = Marshal.StringToHGlobalUni (key);
            secretName.Length = (UInt16) (key.Length * UnicodeEncoding.CharSize);
            secretName.MaximumLength = (UInt16) ((key.Length + 1) * UnicodeEncoding.CharSize);
        }
 
        private IntPtr GetLsaPolicy (LSA_AccessPolicy access) {
            IntPtr LsaPolicyHandle;
            uint ntsResult = LsaOpenPolicy (ref this.localsystem, ref this.objectAttributes, (uint) access, out LsaPolicyHandle);
            uint winErrorCode = LsaNtStatusToWinError (ntsResult);
            if (winErrorCode != 0) {
                throw new Exception ("LsaOpenPolicy failed: " + winErrorCode);
            }
            return LsaPolicyHandle;
        }
 
        private static void ReleaseLsaPolicy (IntPtr LsaPolicyHandle) {
            uint ntsResult = LsaClose (LsaPolicyHandle);
            uint winErrorCode = LsaNtStatusToWinError (ntsResult);
            if (winErrorCode != 0) {
                throw new Exception ("LsaClose failed: " + winErrorCode);
            }
        }
 
        private static void FreeMemory (IntPtr Buffer) {
            uint ntsResult = LsaFreeMemory (Buffer);
            uint winErrorCode = LsaNtStatusToWinError (ntsResult);
            if (winErrorCode != 0) {
                throw new Exception ("LsaFreeMemory failed: " + winErrorCode);
            }
        }
 
        public void SetSecret (string value) {
            LSA_UNICODE_STRING lusSecretData = new LSA_UNICODE_STRING ();
 
            if (value.Length > 0) {
                //Create data and key
                lusSecretData.Buffer = Marshal.StringToHGlobalUni (value);
                lusSecretData.Length = (UInt16) (value.Length * UnicodeEncoding.CharSize);
                lusSecretData.MaximumLength = (UInt16) ((value.Length + 1) * UnicodeEncoding.CharSize);
            } else {
                //Delete data and key
                lusSecretData.Buffer = IntPtr.Zero;
                lusSecretData.Length = 0;
                lusSecretData.MaximumLength = 0;
            }
 
            IntPtr LsaPolicyHandle = GetLsaPolicy (LSA_AccessPolicy.POLICY_CREATE_SECRET);
            uint result = LsaStorePrivateData (LsaPolicyHandle, ref secretName, ref lusSecretData);
            ReleaseLsaPolicy (LsaPolicyHandle);
 
            uint winErrorCode = LsaNtStatusToWinError (result);
            if (winErrorCode != 0) {
                throw new Exception ("StorePrivateData failed: " + winErrorCode);
            }
        }
    }
}
"@
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name "DefaultUserName" -Value "%USERNAME%"
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name "DefaultDomainName" -Value "%DOMAINNAME%"
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name "AutoAdminLogon" -Value "1"
[PInvoke.LSAUtil.LSAutil]::new("DefaultPassword").SetSecret("%PASSWORD%")
Unregister-ScheduledTask -TaskName "CreateAutologon" -Confirm:$false -EA SilentlyContinue
Restart-Computer -Force
'@

function Create-Task ($Argument)
{

    $Schedule = New-Object -ComObject "Schedule.Service"
    $Schedule.Connect('localhost')
    $Folder = $Schedule.GetFolder('\')

    $task = $Schedule.NewTask(0)
    $task.RegistrationInfo.Author = "Onevinn"
    $task.RegistrationInfo.Description = "CreateAutologon"

    $action = $task.Actions.Create(0)
    $action.Path = "PowerShell.exe"
    $action.Arguments = "$Argument"

    $task.Settings.StartWhenAvailable = $true

    $trigger = $task.Triggers.Create(8)
    $trigger.Delay = "PT120S"


    $result = $Folder.RegisterTaskDefinition("CreateAutologon", $task, 0, "SYSTEM", $null, 5)
}

$Code = $Code.Replace("%USERNAME%", $Username)
$Code = $Code.Replace("%DOMAINNAME%", $Domain)
$Code = $Code.Replace("%PASSWORD%", $Password)

$bytes = [System.Text.Encoding]::Unicode.GetBytes($Code)
$b64 = [System.Convert]::ToBase64String($bytes)

Create-Task -Argument "-EncodedCommand $($b64)"

I hope you find this useful

12 thoughts on “Windows 10 Secure AutoLogon – PowerShell”

  1. Michael says:
    August 17, 2020 at 3:27 pm

    Do you use a web service for the OU move?

    Reply
    1. Jörgen Nilsson says:
      August 17, 2020 at 4:59 pm

      Hi, It depends on the customers needs, either PowerShell script like this one: https://ccmexec.com/2018/03/move-the-computer-to-the-correct-ou-during-osd-ps-version/
      or a Webservice, like this one for example https://onevinn.schrewelius.it/Apps01.html

      Regards,
      Jörgen

      Reply
  2. Samuel says:
    August 19, 2020 at 3:35 am

    Bravo. I will mess with this in my dev env. Interesting approach to setting auto login. Thank you

    Reply
  3. Steve says:
    September 10, 2020 at 4:22 pm

    How can I modify this to work outside of the task sequence? I have an offline device that I need to store some credentials in the LSA for cyber security reasons. However the AUTOLOGIN.EXE is not working and I am unable to get this script to work either (even if I remove the TSENV stuff). Running Windows 10 1809. Device is entirely offline and is not managed. I would need this configuration to run as part of a script that executes during first logon.

    Reply
  4. Pingback: Deploy a Windows 10 multi-app kiosk with MEMCM and PowerShell - 4Sysops - CCMEXEC.COM - Enterprise Mobility
  5. Tony says:
    November 6, 2020 at 8:43 am

    Hi Jörgen,
    I implemented AutoLogonPS.ps1 in one of my task sequences. Sadly it only works in like on 1 of 10 tries. After the script runs in my TS, I can see that CreateAutologon exists by using Get-ScheduledTask. After the TS is finished, the Task isn’t there anymore and only DefaultDomain is setup in the registry. Do you have any idea where I should start troubleshooting?

    Reply
  6. Sam says:
    December 9, 2020 at 12:11 pm

    How do I implement this to devices already out there with the clear passwords. We have around 100 kiosk devices that have clear passwords and I need to sort them so the clear password isnt showing. Do I just take out certain steps or is this only if its a fresh device built in SCCM?

    Would be looking for something I can push out via GPO that will remove the clear text, any ideas?

    Reply
  7. DMarv says:
    January 7, 2022 at 6:14 pm

    Will this script work if I do not use TS Variables and instead just regular variables such as $Password= “ThisPassword”
    As Ive done just that but the script does not seem to function as the system reboots and does not AutoLogon. Password verified is correct. Autologon.exe works outside of the TS
    Script also seems to function outside of the TS but does not Autologon after a reboot

    Reply
    1. Jörgen Nilsson says:
      January 10, 2022 at 7:57 am

      HI,
      If you use it outside a TS it will work just fine with password as a variable. But you should use the script that the schedule task runs as that is what configures AutoLogon.
      Regards,
      Jörgen

      Reply
  8. Zee says:
    October 6, 2022 at 4:34 pm

    I’ve set this up as a task sequence and made it ‘Available’ – runs fine on my pc, however I’m seeing after a reboot of the device its attempting to install again, and seems to just be looping on ‘Installing’.
    The TS is set as Available so the behaviour is very odd.

    i seem to have the same issue if i set the Variable on the collection, or in the TS which is my preferred method.

    Also, once it creates the schedule task in step 1 should it reboot automatically, it doesn’t appear to do so for me and I’m having to add a reboot into my TS?

    any help would be greatly appreciated.

    Reply
  9. Ranjan says:
    January 19, 2023 at 5:09 pm

    It is not working. I don’t see any LSA secrets created under HKLM\Security. Any help appreciated

    Reply
  10. Faz says:
    September 5, 2024 at 7:44 am

    Thank you very much!
    It’s exactly what I was looking for!
    Just a point of clarification:
    After several unsuccessful attempts, I’ve found the solution to make this work.
    You mustn’t use a “Reboot” step in the task sequence after the autologon configuration step (script execution).
    I placed the script execution step at the very end of the task sequence, just before the task sequence exit, and completed our post action script with a reboot.
    And now everything works perfectly.
    Many thanks once again!
    (Works on Win10 22H2)

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

My name is Jörgen Nilsson and I work as a Senior Consultant at Onevinn in Malmö, Sweden. This is my blog where I will share tips and stuff for my own and everyone elses use on Enterprise Mobility and Windows related topics.
All code is provided "AS-IS" with no warranties.

Recent Posts

  • New settings in Intune Security Baseline Windows 11 24H2 -2504
  • Managing extensions in Visual Studio Code
  • Reinstall a required Win32app using remediation on demand
  • Administrator protection in Windows 11 – First look
  • Remediation on demand script – ResetWindowsUpdate
©2025 CCMEXEC.COM – Enterprise Mobility | WordPress Theme by Superb Themes
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.Accept Reject Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT