How to Create a Perfect Azure VM using PowerShell?

Here in this article, you will find a fully automated powershell script that creates an Azure VM from Azure compute gallery with proper naming convention of both Network Interface (NIC) and Managed OS Disk with enabled boot diagnostics using managed storage account and Hybrid License benefit.

Step 1: Log in to the Azure Portal

Step 2: Click on the Cloud Shell button in the top right corner of the Azure Portal.

Step 3: Choose the PowerShell (https://portal.azure.com/#cloudshell/)

Note: You can also use Azure Cloud Shell directly from https://shell.azure.com/ if you don't want to open Azure Portal first.

Step 4: Create a powershell file using the following command

code createAzureVM.ps1

Step 5: Add the below automated powershell script in createAzureVM.ps1 file.

<#----------------Switch to Subscrription----------------#>

$sigSubscription = ""
Set-AzContext -SubscriptionName $sigSubscription

<#----------------Define Image Gallery Parameteres----------------#>

$sigRGName = ""
$sigGalleryName = ""
$imageDefName = ""

<#----------------Get Image Version from Shared Image Gallery----------------#>

$imageVersion = Get-AzGalleryImageVersion `
   -ResourceGroupName $sigRGName `
   -GalleryName $sigGalleryName `
   -GalleryImageDefinitionName $imageDefName

$imageVersionID = $imageVersion.Id[-1]

Write-Output "$imageVersionID"

<#----------------Set Variables----------------#>

$Subscription=""

$RGName = ""
$Location="eastus"

$VNetName = ""
$SubnetName = "default"
$subnetaddressprefix = "10.1.0.0/24"
$NICName = ""

$VMName = "VM01"
$ComputerName = "VM01"
$VMSize = "Standard_D2as_v4"
$Username = ""
$Password = "" | ConvertTo-SecureString -Force -AsPlainText
$newOsDiskName = ""

$PublisherName = "MicrosoftWindowsServer2019"
$Offer = "WindowsServer2019"
$Skus = "2019DatacenterGen2"

$SkuName="Premium_LRS" #Premium_LRS #Standard_LRS
$Licence="Windows_Server" #"Windows_Client" for clients and "Windows_Server" for servers

Write-Output -InputObject "Collecting the resources to create the Virtual machine .."

<#----------------Switch to Subscrription----------------#>

Set-AzContext -SubscriptionName "$Subscription"

<#-------------------------- Store Subscription Details -----------------------------#>

$SubscriptionId = Get-AzSubscription | Where-Object {$_.Name -eq $Subscription} | Select-Object -Property id
$Subscriptionidvalue = $SubscriptionId.Id

<#-------------------------- Virtual Network/ Subnet/Network Interface-----------------------------#>

$vnet = Get-AzVirtualNetwork  -Name $VNetName

if (!(Get-AzVirtualNetworkSubnetConfig -Name $SubnetName -VirtualNetwork $vnet -ErrorAction:Ignore) ) {
    Add-AzVirtualNetworkSubnetConfig -Name $SubnetName -VirtualNetwork $vnet -AddressPrefix $subnetaddressprefix -WarningAction:SilentlyContinue | Out-Null #make this comment if already subnet is there
    Write-Output -InputObject "Subnet $SubnetName created."
}
else{
    Write-Output -InputObject "Subnet $SubnetName  already exists"
}

Set-AzVirtualNetwork -VirtualNetwork $vnet

$resourcegname = $vnet.ResourceGroupName

#/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/ResourceGroup1/providers/Microsoft.Network/virtualNetworks/VirtualNetwork1/subnets/XsubnetnameX'

$SubnetId="/subscriptions/$Subscriptionidvalue/resourceGroups/$resourcegname/providers/Microsoft.Network/virtualNetworks/$VNetName/subnets/$SubnetName"

if (!(Get-AzNetworkInterface -Name $NicName -ResourceGroupName $RGName -ErrorAction:Ignore)){
    $nic = New-AzNetworkInterface -Name $NicName -ResourceGroupName $RGName -Location $location -SubnetId $SubnetId
    $nic | Out-Null
    Write-Output -InputObject "Network interface $NicName Created."
}
else{
    Write-Output -InputObject "Network interface $NicName Already Exists."
}

$nic = Get-AzNetworkInterface -Name $NicName -ResourceGroupName $RGName

<#-------------------------- VM Credentials -----------------------------#>

Write-Output -InputObject "Defining the  credential object to store the username and password for the virtual machine.."
$Credential = New-Object -TypeName PSCredential -ArgumentList ($Username, $Password)

<#-------------------------- Set VM Configuration -----------------------------#>

Write-Output -InputObject "Creating the virtual machine configuration object.."
$VirtualMachine = New-AzVMConfig -VMName $VMName -VMSize $VMSize

<#-------------------------- Set VM Computer Name and Credentials -----------------------------#>

Write-Output -InputObject "Setting the VM Size and Type.."
$VirtualMachine = Set-AzVMOperatingSystem -VM $VirtualMachine -Windows -ComputerName $ComputerName -Credential $Credential

<#-------------------------- Enable Provisioning VM Agent -----------------------------#>

Write-Output -InputObject "Enabling the provisioning of the VM Agent.."
if ($VirtualMachine.OSProfile.WindowsConfiguration) {
    $VirtualMachine.OSProfile.WindowsConfiguration.ProvisionVMAgent = $true
}

$VirtualMachine = Set-AzVMSourceImage -VM $VirtualMachine -Id $imageVersionID

# Add Network Interface Card
Write-Output -InputObject "Adding the Network Interface Card.."
$VirtualMachine = Add-AzVMNetworkInterface -Id $nic.Id -VM $VirtualMachine

# Applies the OS disk properties
Write-Output -InputObject "Appling the OS disk properties.."
$VirtualMachine = Set-AzVMOSDisk -VM $VirtualMachine -CreateOption "FromImage"

<#-------------------------- Enable/Disable Azure VM Boot Diagnostics -----------------------------#>

#$VirtualMachine = Set-AzVMBootDiagnostic -VM $VirtualMachine -Enable -StorageAccountName $SAName -ResourceGroupName $RGName
$VirtualMachine = Set-AzVMBootDiagnostic -VM $VirtualMachine -Disable

<#-------------------------- Create Azure VM -----------------------------#>

Write-Output -InputObject "Creating Virtual Machine"
$NewVM = New-AzVM -ResourceGroupName $RGName -Location $Location -VM $VirtualMachine

<#-------- Adding Hybrid Benefit Licencing to the Machine --------------#>

Write-Output -InputObject "Adding Hybrid Benefit Licencing to the Machine .. "
$virtualMachine.LicenseType = $Licence

Step 6: Once you are done modifying the file with required details. Execute the file using the following run command.

./createAzureVM.ps1