JSON Azure deployment: Create PowerShell script during CSE to allow scripting to continue after a reboot

While working on a JSON Azure deployment we came across a scenario where we were needing to script after a reboot from the Custom Script Extension (CSE). This can’t be done out of the box as once the server reboots, the CSE module stops running. To work around this we used the RunOnce, and AutoAdminLogon registry keys to Auto login then run a PowerShell script to finish off the JSON deployment.

This involved creating the 4 registry keys and the PowerShell script, which was all done using the CSE, during the JSON deployment, the code for this is shown below:

#region add auto logon reg key – this allows the admin account to log into the server after reboot
Write-Output “$(Get-Date) | Creating Reg Values for Auto Logon”
$registryPath = “HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon”

$Name = “DefaultUserName”

$value = “<domain>\<domain admin account>”

New-ItemProperty -Path $registryPath -Name $name -Value $value -Force | Out-Null
###

$registryPath = “HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon”

$Name = “DefaultPassword”

$value = “<password>”

New-ItemProperty -Path $registryPath -Name $name -Value $value -Force | Out-Null
###
$registryPath = “HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon”

$Name = “DefaultDomainName”

$value = “<domain name>”

New-ItemProperty -Path $registryPath -Name $name -Value $value -Force | Out-Null
###

$registryPath = “HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon”

$Name = “AutoAdminLogon”

$value = “1”

New-ItemProperty -Path $registryPath -Name $name -Value $value -PropertyType DWORD -Force | Out-Null
Write-Output “$(Get-Date) | Finished Creating Reg Values for Auto Logon”
#endregion

#region create powershell script for 2nd server – the script is specified in the install2 variable then created in the media location
Write-Output “$(Get-Date) | Creating PowerShell Script for RunOnce  Install”
$install2 = {

<PowerShell Code>

}

New-Item c:\Install\Install2.ps1 -type file -force -value “$install2”
Write-Output “$(Get-Date) | Finished Creating PowerShell Script for RunOnce  Install”
#endregion

#region create RunOnce reg key – this allows the above powershell script to be ran on the next startup
Write-Output “$(Get-Date) | Creating RunOnce Reg Key”
set-itemproperty “HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce” “!NextRun” (‘C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe -executionPolicy Unrestricted -File ‘ + “c:\Install\Install2.ps1”)
Write-Output “$(Get-Date) | Finished Creating RunOnce Reg Key”
#endregion

#Once the server restarts the Powershell script will be ran to finish installing the server.
Restart-Computer

Enterprise Mobility Workshops - 24th November 2015 - London | 9:00am – 3:00pm

Leave a Reply

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