Learning and Sharing
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
No Result
View All Result

How to Create a Azure VM using PowerShell

May 18, 2024
in Blog, Microsoft Azure, Powershell
0
ADVERTISEMENT

Table of Contents

The Azure PowerShell module is used to create and manage Azure resources from the PowerShell command line or in scripts. This quickstart shows you how to use the Azure PowerShell module to deploy a virtual machine (VM) in Azure.

Connect to Microsoft Azure PowerShell

First, you need connect to Microsoft Azure PowerShell, there’re two ways to run PowerShell commands in Microsoft Azure:

Method 1: From Azure PowerShell modules installed in a computer.

Bg1624

Method 2: From Azure Cloud Shell using browsers.

Bg1625

Create a new Windows VM in Azure using PowerShell

1. Gets all locations.

Get-AzLocation | select DisplayName, Location, Type, GeographyGroup
DisplayName          Location             Type GeographyGroup
-----------          --------             ---- --------------
East US              eastus             Region US
East US 2            eastus2            Region US
South Central US     southcentralus     Region US
West US 2            westus2            Region US
West US 3            westus3            Region US
Australia East       australiaeast      Region Asia Pacific
Southeast Asia       southeastasia      Region Asia Pacific
North Europe         northeurope        Region Europe
Sweden Central       swedencentral      Region Europe
UK South             uksouth            Region Europe
West Europe          westeurope         Region Europe
....

2. The Azure marketplace includes many images that can be used to create a new VM. Run The below command to return a list of image publishers in a location.

Get-AzVMImagePublisher -Location "EastUS" | where PublisherName -like *windows*
PublisherName                                                 Location
-------------                                                 --------
Microsoft.WindowsAdminCenter.Test                             eastus
SentinelOne.WindowsExtension.Test                             eastus
Chef.Bootstrap.WindowsAzure                                   eastus
Microsoft.Windows.Azure.Extensions                            eastus
MicrosoftWindowsDesktop                                       eastus
Microsoft.VisualStudio.WindowsAzure.DevTest.Test              eastus
Microsoft.VisualStudio.WindowsAzure.RemoteDebug               eastus
MicrosoftWindowsServer                                        eastus
MicrosoftWindowsServerHPCPack                                 eastus
....

3. Use the Get-AzVMImageOffer to return a list of image offers. With this command, the returned list is filtered on the specified publisher named MicrosoftWindowsServer:

Get-AzVMImageOffer -Location "EastUS" -PublisherName "MicrosoftWindowsServer"
Offer                                    PublisherName          Location
-----                                    -------------          --------
19h1gen2servertest                       MicrosoftWindowsServer eastus
microsoftserveroperatingsystems-previews MicrosoftWindowsServer eastus
servertesting                            MicrosoftWindowsServer eastus
windows-cvm                              MicrosoftWindowsServer eastus
WindowsServer                            MicrosoftWindowsServer eastus
windowsserver-gen2preview                MicrosoftWindowsServer eastus
windowsserver-previewtest                MicrosoftWindowsServer eastus
windowsserverdotnet                      MicrosoftWindowsServer eastus
windowsserverhotpatch-previews           MicrosoftWindowsServer eastus
WindowsServerSemiAnnual                  MicrosoftWindowsServer eastus
windowsserverupgrade                     MicrosoftWindowsServer eastus
....

4. The Get-AzVMImageSku command will then filter on the publisher and offer name to return a list of image names.

Get-AzVMImageSku `
   -Location "EastUS" `
   -PublisherName "MicrosoftWindowsServer" `
   -Offer "WindowsServer"
Skus                                      Offer         PublisherName          Location
----                                      -----         -------------          --------
2008-R2-SP1                               WindowsServer MicrosoftWindowsServer EastUS  
2008-R2-SP1-smalldisk                     WindowsServer MicrosoftWindowsServer EastUS  
2012-Datacenter                           WindowsServer MicrosoftWindowsServer EastUS  
2012-Datacenter-smalldisk                 WindowsServer MicrosoftWindowsServer EastUS  
2012-R2-Datacenter                        WindowsServer MicrosoftWindowsServer EastUS  
2012-R2-Datacenter-smalldisk              WindowsServer MicrosoftWindowsServer EastUS  
2016-Datacenter                           WindowsServer MicrosoftWindowsServer EastUS  
2016-Datacenter-Server-Core               WindowsServer MicrosoftWindowsServer EastUS  
2016-Datacenter-Server-Core-smalldisk     WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter-smalldisk                 WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter-with-Containers           WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter-with-Containers-smalldisk WindowsServer MicrosoftWindowsServer EastUS
2016-Datacenter-with-RDSH                 WindowsServer MicrosoftWindowsServer EastUS
2016-Nano-Server                          WindowsServer MicrosoftWindowsServer EastUS
....

5. Next, find available VM sizes. To see a list of VM sizes available in a particular region, use the Get-AzVMSize command.

Get-AzVMSize -Location "EastUS" | where NumberOfCores  -eq 4
Name                   NumberOfCores MemoryInMB MaxDataDiskCount OSDiskSizeInMB ResourceDiskSizeInMB
----                   ------------- ---------- ---------------- -------------- --------------------
Standard_D4a_v4                    4      16384                8        1047552               102400
Standard_D4as_v4                   4      16384                8        1047552                32768
Standard_E4a_v4                    4      32768                8        1047552               102400
Standard_E4-2as_v4                 4      32768                8        1047552                65536
Standard_E4as_v4                   4      32768                8        1047552                65536
Standard_D4as_v5                   4      16384                8        1047552                    0
Standard_E4-2as_v5                 4      32768                8        1047552                    0
Standard_E4as_v5                   4      32768                8        1047552                    0
Standard_D4ads_v5                  4      16384                8        1047552               153600
....

The above information can be used to deploy a VM with a specific image. This example deploys a VM using the latest version of a Windows 10 Pro using PowerShell.

# Don't forget to change the variables to fit with yours.
$num            = $(Get-Random)
$rgname         = "RG-$num"
$loc            = "eastus"
$vmname         = "vm-$num"
$vnetname       = "vnet-$num"
$vnetAddress    = "10.0.0.0/16"
$subnetname     = "subnet-$num"
$subnetAddress  = "10.0.2.0/24"
$NICName        = $vmname + "-nic"
$NSGName        = $vmname + "-NSG"
$VMSize         = "Standard_DS2_v2"
$PublisherName  = "microsoftwindowsdesktop"
$Offer          = "Windows-10"
$SKU            = "win10-22h2-pro-g2"
$version        = "latest"
$password       = "Pass@ord123"
$adminUsername  = 'bonguides'
$securePassword = $password | ConvertTo-SecureString -AsPlainText -Force
$Credential     = New-Object System.Management.Automation.PSCredential ($adminUsername, $securePassword)

Write-Host "Creating a resource group..." -ForegroundColor Green
$null = New-AzResourceGroup -Name $rgName -Location $Loc

# Network setup
Write-Host "Setting up the network..." -ForegroundColor Green
$frontendSubnet = New-AzVirtualNetworkSubnetConfig -Name $subnetname -AddressPrefix $subnetAddress
$vnet           = New-AzVirtualNetwork -Name $vnetname -ResourceGroupName $rgname -Location $loc -AddressPrefix $vnetAddress -Subnet $frontendSubnet
$nsgRuleRDP     = New-AzNetworkSecurityRuleConfig -Name RDP  -Protocol Tcp  -Direction Inbound -Priority 1001 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange 3389 -Access Allow
$nsg            = New-AzNetworkSecurityGroup -ResourceGroupName $RGName -Location $loc -Name $NSGName  -SecurityRules $nsgRuleRDP
$pip            = New-AzPublicIpAddress -ResourceGroupName $rgName -Location $loc -Name "mypublicdns$(Get-Random)" -AllocationMethod Static -IdleTimeoutInMinutes 4
$nic            = New-AzNetworkInterface -Name $NICName -ResourceGroupName $RGName -Location $loc -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id -EnableAcceleratedNetworking
$vmConfig       = New-AzVMConfig -VMName $vmName -VMSize $VMSize
$null           = Set-AzVMOperatingSystem -VM $vmConfig -Windows -ComputerName $vmName -Credential $Credential
$null           = Set-AzVMSourceImage -VM $vmConfig -PublisherName $PublisherName -Offer $Offer -Skus $SKU -Version $version 
$null           = Add-AzVMNetworkInterface -VM $vmConfig -Id $nic.Id

Write-Host "Creating the Azure VM..." -ForegroundColor Green
New-AzVM -ResourceGroupName $rgname -Location $loc -VM $vmConfig -WarningAction silentlyContinue

# Waiting for the VM starts
Write-Host "Waiting for the VM starts..." -ForegroundColor Green
Start-Sleep -Seconds 30

# Install required apps unattended.
$fileUri = @("https://raw.githubusercontent.com/bonguides25/PowerShell/main/Utilities/Files/new_az_vm_with_apps.ps1")
$protectedSettings = @{"commandToExecute" = "powershell.exe -ExecutionPolicy Unrestricted -File new_az_vm_with_apps.ps1"}
$settings = @{"fileUris" = $fileUri}

Write-Host "Install required apps unattended..." -ForegroundColor Green
$null = Set-AzVMExtension -ResourceGroupName $rgname -Location $loc -VMName $vmname -Name "MyCustomScriptExtension" -Publisher "Microsoft.Compute" -ExtensionType "CustomScriptExtension" -TypeHandlerVersion "1.10" -Settings $settings -ProtectedSettings $protectedSettings

# After the deployment has completed, create a remote desktop connection with the VM
Write-Host "Connecting using RDP..." -ForegroundColor Green
$rdpip = Get-AzPublicIpAddress -ResourceGroupName $rgname | Select-Object IpAddress
$null = cmdkey /generic:($rdpip).IPAddress /user:"$adminUsername" /pass:"$password"
$null = mstsc /v:($rdpip).IPAddress /w:1366 /h:768
ADVERTISEMENT

Not a reader? Watch this related video tutorial:

5/5 - (1 vote)
Previous Post

How to Find Azure Marketplace VM Images with Azure PowerShell

Next Post

How to Assign a Network Security Group in Azure using PowerShell

Related Posts

Running Hyper-V and VMware Workstation on The Same Machine

August 15, 2024

How to Uninstall All Autodesk Products At Once Silently

July 29, 2024
Ftr5

How to Uninstall the Autodesk Genuine Service on Windows

July 29, 2024
Ftr19

How to Fix Windows Cannot Read the ProductKey From the Unattend Answer File in VirtualBox

July 26, 2024
Ftr25

How to Update Windows Terminal in Windows 10/11

July 26, 2024

How to Disable The Beep Sound in WSL Terminal on Windows

July 26, 2024

Leave a Reply Cancel reply

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

Recent Posts

  • How To Turn On uBlock Origin Extension in Chrome (2025)
  • Images Hidden Due To Mature Content Settings In CivitAI
  • Azure OpenAI vs Azure AI Hub, How to Choose the Right One for Your Needs

Categories

Stay in Touch

Discord Server

Join the Discord server with the site members for all questions and discussions.

Telegram Community

Jump in Telegram server. Ask questions and discuss everything with the site members.

Youtube Channel

Watch more videos, learning and sharing with Leo ❤❤❤. Sharing to be better.

Newsletter

Join the movement and receive our weekly Tech related newsletter. It’s Free.

General

Microsoft Windows

Microsoft Office

VMware

VirtualBox

Technology

PowerShell

Microsoft 365

Microsoft Teams

Email Servers

Copyright 2025 © All rights Reserved. Design by Leo with ❤

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory