AutoLogon.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
#Define ASCII Characters
    $Equals = [Char]61
    $Space = [Char]32
    $SingleQuote = [Char]39
    $DoubleQuote = [Char]34
    $NewLine = "`n"

#Load WMI Classes
    $OperatingSystem = Get-WmiObject -Namespace "root\CIMv2" -Class "Win32_OperatingSystem" -Property * | Select *

#Define Functions
    #Retrieve The Value Of A Registry Path
        Function Get-RegistryValue
            {
                [CmdletBinding(SupportsShouldProcess=$True)]
                Param
                    (
                        [Parameter(Mandatory=$True)]
                        [String]$Path, 
                        
                        [Parameter(Mandatory=$True)]
                        [String]$Name
                    )
                
                If (Test-Path -Path $Path -ErrorAction SilentlyContinue)
                    {
                        Write-Verbose -Message "Now retrieving value `"$($Name)`" from `"$($Path)`""
                        $Result = (Get-ItemProperty -Path $Path -Name $Name | Select -ExpandProperty $Name | Out-String).Trim()
                    }
                Else
                    {
                        $Result = $Null
                    }
                
                Return $Result
            }
    
    #Set The Value Of A Registry Path
        Function Set-RegistryValue
            {
                [CmdletBinding(SupportsShouldProcess=$True)]
                    Param
                        (
                            [Parameter(Mandatory=$True)]
                            [ValidateScript({$_ -like "HK*:*"})]
                            [String]$Path, 
                        
                            [Parameter(Mandatory=$True)]
                            [String]$Name,
                        
                            [Parameter(Mandatory=$True)]
                            $Value,

                            [Parameter(Mandatory=$True)]
                            [ValidateSet("Binary","DWord","ExpandString","MultiString","String","QWord")]
                            [String]$ValueType
                        )
                
                $PSDrive_Name = $Path.Split(":")[0]

                If ($PSDrive_Name -eq "HKCR") {$PSDrive_Root = "HKEY_CLASSES_ROOT"}
                If ($PSDrive_Name -eq "HKCU") {$PSDrive_Root = "HKEY_CURRENT_USER"}
                If ($PSDrive_Name -eq "HKLM") {$PSDrive_Root = "HKEY_LOCAL_MACHINE"}
                If ($PSDrive_Name -eq "HKU") {$PSDrive_Root = "HKEY_USERS"}
                If ($PSDrive_Name -eq "HKCC") {$PSDrive_Root = "HKEY_CURRENT_CONFIG"}
                
                If (!(Get-PSDrive -Name $PSDrive_Name -PSProvider Registry -ErrorAction SilentlyContinue)) {$PSDrive_Create = New-PSDrive -Name $PSDrive_Name -Root $PSDrive_Root -PSProvider Registry}
                
                If (!(Test-Path -Path $Path -ErrorAction SilentlyContinue))
                    {
                        New-Item -Path $Path -Force | Out-Null
                    }

                New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $ValueType -Force | Out-Null

                If ($? -eq $True)
                    {
                        Write-Verbose -Message "Set-RegistryValue: `"$($Name)`" of type `"$($ValueType)`" with value of `"$($Value)`" in path `"$($Path)`" was successful"
                    }
                Else
                    {
                        Write-Error -Message "Set-RegistryValue: `"$($Name)`" of type `"$($ValueType)`" with value of `"$($Value)`" in path `"$($Path)`" was unsuccessful"
                    }
            }
<#
 
.Synopsis
This powershell cmdlet enables AutoLogon the next time the device reboots. Can be configured to only require a logoff. Additionally, a command can executed upon login.
 
-Domain : Provide the domain of the user to be logged in. Default is the local workstation.
-Username : Provide the username that the system will use to login.
-Password : Provide the password for the username provided. Must be of type [System.Security.SecureString].
-LogonCount : Sets the number of times the system would reboot without asking for credentials. Default is 1.
-ForceAutoLogon : Force auto logon without a restart. A logoff would be sufficient.
-AsynchronousRunOnce : Allows the Windows interface to load while running the command specified in the command parameter.
-Command : Provide the command that will be executed after the device is restarted. Example : $($PSHome)\powershell.exe -ExecutionPolicy Bypass -NoLogo -WindowStyle Maximized -File `"$($Env:Windir)\Temp\MyPowershellScript.ps1`"
-DefaultCommand : Places the default command into the run once registry key, which is just a full screen non terminating powershell console.
-Interactive : Prompts for credentials using (Get-Credential) instead of using the values supplied by the arguments.
 
.Description
Enables AutoLogon.
 
.Example
Enable-AutoLogon -Interactive -DefaultCommand -ForceAutoLogon
 
.Example
Enable-AutoLogon -Username "Administrator" -Password (ConvertTo-SecureString -String "YourPassword" -AsPlainText -Force)
 
.Example
Enable-AutoLogon -Username "Administrator" -Password (ConvertTo-SecureString -String "YourPassword" -AsPlainText -Force) -LogonCount "3"
 
.Example
Enable-AutoLogon -Username "Administrator" -Password (ConvertTo-SecureString -String "YourPassword" -AsPlainText -Force) -Command "$($PSHome)\powershell.exe -ExecutionPolicy Unrestricted -NoLogo -WindowStyle Maximized -File `"$($Env:Windir)\Temp\MyPowershellScript.ps1`""
 
.Example
Enable-AutoLogon -Username "Administrator" -Password (ConvertTo-SecureString -String "YourPassword" -AsPlainText -Force) -AsynchronousRunOnce -Command "$($PSHome)\powershell.exe -ExecutionPolicy Unrestricted -NoLogo -WindowStyle Maximized -File `"$($Env:Windir)\Temp\MyPowershellScript.ps1`""
 
#>


Function Enable-AutoLogon
    {
        [CmdletBinding()]
            Param
                (
                    [Parameter(Mandatory=$False,ValueFromPipeline=$True,Position=0)]
                    [Alias("DMN")]
                    [String]$Domain = "$($Env:UserDomain)",
                    
                    [Parameter(Mandatory=$False,ValueFromPipeline=$True,Position=1)]
                    [Alias("UN")]
                    [String]$Username = "$($Env:Username)",

                    [Parameter(Mandatory=$False,ValueFromPipeline=$True,Position=2)]
                    [Alias("PW")]
                    [ValidateNotNullOrEmpty()]
                    [System.Security.SecureString]$Password,

                    [Parameter(Mandatory=$False,ValueFromPipeline=$True,Position=3)]
                    [AllowEmptyString()]
                    [Alias("LC")]
                    [UInt32]$LogonCount = "1",

                    [Parameter(Mandatory=$False,ValueFromPipeline=$True,Position=4)]
                    [Alias("FAL")]
                    [Switch]$ForceAutoLogon,
                    
                    [Parameter(Mandatory=$False,ValueFromPipeline=$True,Position=5)]
                    [Alias("ASRO")]
                    [Switch]$AsynchronousRunOnce,
                    
                    [Parameter(Mandatory=$False,ValueFromPipeline=$True,Position=6)]
                    [AllowEmptyString()]
                    [Alias("Script")]
                    [String]$Command = "$($PSHome)\powershell.exe -ExecutionPolicy Unrestricted -NoLogo -NoExit -WindowStyle Maximized",
                    
                    [Parameter(Mandatory=$False,ValueFromPipeline=$True,Position=7)]
                    [Alias("DC")]
                    [Switch]$DefaultCommand,
                    
                    [Parameter(Mandatory=$False,ValueFromPipeline=$True,Position=8)]
                    [Alias("ShowUI")]
                    [Switch]$Interactive    
                )

            Begin
                {
                    $RegistryPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
                    $RegistryRunOncePath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
                    $RegistryAsynchronousRunOncePath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer"
                }
    
            Process
                {
                    Try
                        {
                            If ($Interactive.IsPresent)
                                {
                                    $Credentials = (Get-Credential -Message "Please enter the credentials that will be used for AutoLogon" -UserName "$($Domain)\$($Username)").GetNetworkCredential()
                                    $Domain = $Credentials.Domain
                                    $Username = $Credentials.UserName
                                    $Password = $Credentials.SecurePassword
                                }

                            [String]$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))

                            Set-RegistryValue -Path $RegistryPath -Name "AutoAdminLogon" -Value "1" -ValueType String
                            Set-RegistryValue -Path $RegistryPath -Name "DefaultUsername" -Value $Username -ValueType String
                            Set-RegistryValue -Path $RegistryPath -Name "DefaultPassword" -Value $UnsecurePassword -ValueType String
                            Set-RegistryValue -Path $RegistryPath -Name "DefaultDomainName" -Value $Domain -ValueType String
                                    
                            If ($PSBoundParameters.ContainsKey("LogonCount"))
                                {
                                    Set-RegistryValue -Path $RegistryPath -Name "AutoLogonCount" -Value $LogonCount -ValueType Dword 
                                }
                            Else
                                {
                                    Set-RegistryValue -Path $RegistryPath -Name "AutoLogonCount" -Value $LogonCount -ValueType Dword
                                }
            
                            If ($PSBoundParameters.ContainsKey("Command") -and ($DefaultCommand.IsPresent -eq $False))
                                {
                                    Set-RegistryValue -Path $RegistryRunOncePath -Name "(Default)" -Value $Command -ValueType String
                                }
                            ElseIf (!$PSBoundParameters.ContainsKey("Command") -and ($DefaultCommand.IsPresent -eq $True))
                                {
                                    Set-RegistryValue -Path $RegistryRunOncePath -Name "(Default)" -Value $Command -ValueType String
                                }
                            Else
                                {
                                    Set-RegistryValue -Path $RegistryRunOncePath -Name "(Default)" -Value "" -ValueType String
                                }
                        
                            If ($ForceAutoLogon.IsPresent)
                                {
                                    Set-RegistryValue -Path $RegistryPath -Name "ForceAutoLogon" -Value "1" -ValueType String
                                }
                            Else
                                {
                                    Set-RegistryValue -Path $RegistryPath -Name "ForceAutoLogon" -Value "0" -ValueType String
                                }
                            
                            If ($AsynchronousRunOnce.IsPresent)
                                {
                                    Set-RegistryValue -Path $RegistryAsynchronousRunOncePath -Name "AsyncRunOnce" -Value "1" -ValueType Dword
                                }
                            Else
                                {
                                    Set-RegistryValue -Path $RegistryAsynchronousRunOncePath -Name "AsyncRunOnce" -Value "0" -ValueType Dword
                                }
                        }
                    Catch
                        {
                            Write-Output -InputObject $Error
                        }
                }
    }

<#
.Synopsis
This powershell cmdlet disables AutoLogon completely.
 
.Description
Disables AutoLogon.
 
.Example
Disable-AutoLogon
#>


Function Disable-AutoLogon
    {
        Begin
            {
                $RegistryPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
                $RegistryRunOncePath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
                $RegistryAsynchronousRunOncePath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer"
            }
    
        Process
            {
                Try
                    {
                        Set-RegistryValue -Path $RegistryPath -Name "AutoAdminLogon" -Value "0" -ValueType String
                        Set-RegistryValue -Path $RegistryPath -Name "DefaultUsername" -Value "" -ValueType String
                        Set-RegistryValue -Path $RegistryPath -Name "DefaultPassword" -Value "" -ValueType String
                        Set-RegistryValue -Path $RegistryPath -Name "DefaultDomainName" -Value "" -ValueType String
                        Set-RegistryValue -Path $RegistryPath -Name "AutoLogonCount" -Value "" -ValueType Dword
                        Set-RegistryValue -Path $RegistryPath -Name "ForceAutoLogon" -Value "0" -ValueType String
                        Set-RegistryValue -Path $RegistryRunOncePath -Name "(Default)" -Value "" -ValueType String        
                        If ([Version]($OperatingSystem.Version) -lt [Version]"10.0")
                            {
                                Set-RegistryValue -Path $RegistryAsynchronousRunOncePath -Name "AsyncRunOnce" -Value "0" -ValueType Dword
                            }
                        ElseIf ([Version]($OperatingSystem.Version) -ge [Version]"10.0")
                            {
                                Set-RegistryValue -Path $RegistryAsynchronousRunOncePath -Name "AsyncRunOnce" -Value "1" -ValueType Dword
                            }
                    }
                Catch
                    {
                        Write-Output -InputObject $Error
                    }
            }
    }

<#
 
.Synopsis
 
This powershell cmdlet allows you to retrieve the current phase of a phased autologon routine.
 
You could for example get the current phase and run an additional command/script based on the phase value.
 
If ((Get-Phase) -eq "1") {Enable-AutoLogon -Username "Administrator" -Password (ConvertTo-SecureString -String "YourPassword" -AsPlainText -Force) -AsynchronousRunOnce -Command "$($PSHome)\powershell.exe -ExecutionPolicy Unrestricted -NoLogo -WindowStyle Maximized -File `"$($Env:Windir)\Temp\MyPowershellScript1.ps1`""}
 
If ((Get-Phase) -eq "2") {Enable-AutoLogon -Username "Administrator" -Password (ConvertTo-SecureString -String "YourPassword" -AsPlainText -Force) -AsynchronousRunOnce -Command "$($PSHome)\powershell.exe -ExecutionPolicy Unrestricted -NoLogo -WindowStyle Maximized -File `"$($Env:Windir)\Temp\MyPowershellScript2.ps1`""}
 
.Example
Get-Phase
 
#>


Function Get-Phase
    {
        [CmdletBinding()]
            Param
                (
                )
                    Begin
                        {
                            [String]$Path = "HKLM:\SOFTWARE\Modules\AutoLogon"
                            [String]$Name = "Phase"
                            [String]$Value = "1"
                        }
                    
                    Process
                        {
                            Try
                                {   
                                    If (Get-RegistryValue -Path $Path -Name $Name)
                                        {
                                            $ScriptPhase = Get-RegistryValue -Path $Path -Name $Name
                                        }
                                    Else
                                        {
                                            Write-Warning -Message "`"$($Path)`" not found. Please use the `"Set-Phase`" cmdlet to set the phase first."
                                        }
                            
                                    If ($ScriptPhase) {Return $ScriptPhase}
                                }
                            Catch
                                {
                                    Write-Output -InputObject $Error
                                }
                        }
    }

<#
 
.Synopsis
This powershell cmdlet allows the phase to be set while still running a script.
 
.Description
This powershell cmdlet allows the phase to be set while still running a script. Somewhere at the end of a script, set the phase and enable autologon. Once the devices reboots and runs the script, it will conditionally execute the code relative to phase 2 for example. Ultimately, the ability to string together reboots, autologons, and script execution, you will be able to fully prepare a computer.
 
.Example
Set-Phase -Phase "2"
 
#>


Function Set-Phase
    {
        [CmdletBinding()]
            Param
                (
                    [Parameter(Mandatory=$False,ValueFromPipeline=$True,Position=0)]
                    [ValidateNotNullOrEmpty()]
                    [String]$Phase = "1"   
                )
                    Begin
                        {
                            [String]$Path = "HKLM:\SOFTWARE\Modules\AutoLogon"
                            [String]$Name = "Phase"
                        }
                    Process
                        {
                            Try
                                {
                                    Set-RegistryValue -Path $Path -Name $Name -Value $Phase -ValueType String 
                                }
                            Catch
                                {
                                    Write-Error -InputObject $Error
                                }
                        }
    }

<#
 
.Synopsis
This powershell cmdlet removes phase information from the registry. Useful for cleanup in scripts
 
.Description
This powershell cmdlet removes phase information from the registry. Useful for cleanup in scripts
 
.Example
Remove-Phase
 
#>


Function Remove-Phase
    {
        [CmdletBinding()]
            Param
                (
                )
                    Begin
                        {
                            [String]$Path = "HKLM:\SOFTWARE\Modules\AutoLogon"
                        }

                    Process
                        {
                            Try
                                {
                                    Remove-Item -Path $Path -Recurse -Force       
                                }   
                            Catch
                                {
                                    Write-Output -InputObject $Error
                                }
                    }
    }

#Export Module Functions
    Export-ModuleMember -Function "Enable-AutoLogon", "Disable-AutoLogon", "Get-Phase", "Set-Phase", "Remove-Phase"