e-Zest members share technology ideas to foster digital transformation.

To create remote Azure VM with PowerShell (automation)

Written by Kunal Patil | Sep 1, 2015 7:10:47 PM


Create the VM with pre-configuration such as installed windows features and roles.

Step 1: Create new VM script:

You have to create a script to get new Azure VM ready with provided details. You need to then inject one script (custom script) with other script (Azure automation).

Let us view a script for creating new vm as follows:

  • #Add-AzureAccount
  • $vm = New-AzureVMConfig -Name $VMname -InstanceSize Small -ImageName $IMAGE
  • Add-AzureProvisioningConfig -VM $vm -Windows -AdminUsername "$USER" -Password “$Password "
  • Set-AzureVMCustomScriptExtension -ContainerName vhds -filename 'custom.ps1' -Run custom.ps1 -VM $vm -verbose
  • $vm = New-AzureVM -ServiceName $CLOUDSERVICE -Location $location -VMs $vm
  • Get-Azurevm -ServiceName $CLOUDSERVICE -Name $VMname | Update-AzureVM

Step 2: Inject script:

While creating Azure VM with GUI, put this as custom script

But with command line for automation, we need to put custom script in Azure storage that is blob (recommended). For injecting the script which is required for installing pre-requisites such as windows roles and features installation, create a custom script. Store it on Azure blob. Call it with the following syntax:

Set-AzureVMCustomScriptExtension -VM $vm -ContainerName vhds -filename 'custom.ps1'

Here custom.ps1 is another ps script which has to be injected on Azure vm using the following steps:

  • Set-ExecutionPolicy RemoteSigned
  • Install-WindowsFeature Web-Server -IncludeManagementTools -IncludeAllSubFeature
  • Install-WindowsFeature -Name DNS , RDC
  • Install-WindowsFeature DHCP, Storage-Services, WDS,NET-Framework-Features
  • Install-WindowsFeature -Name UpdateServices -IncludeManagementTools
  • Install-WindowsFeature AD-Domain-Services
  • Import-Module ADDSDeployment
  • Install-ADDSForest `
  • CreateDnsDelegation:$false `
  • SafeModeAdministratorPassword (convertto-securestring "pass@123" -asplaintext -force)
  • DatabasePath "C:\Windows\NTDS" `
  • DomainMode "Win2008R2" `
  • DomainName "ezest.demo" `
  • DomainNetbiosName "EZEST" `
  • ForestMode "Win2008R2" `
  • InstallDns:$true `
  • LogPath "C:\Windows\NTDS" `
  • NoRebootOnCompletion:$false `
  • SysvolPath "C:\Windows\SYSVOL" `
  • -Force:$true[/checklist]

Install-WindowsFeature BITS -IncludeAllSubFeature -IncludeManagementTools -Restart

Step 3: Now run script with PowerShell. The VM is ready with all the necessary prerequisites.

Note: Check for Default azure storage account and Azure account before running script.

Use the following command for current Azure account as well as storage account

Get-AzureSubscription