Quickstart: Create a Virtual Machine with PowerShell

This quickstart guide walks you through creating a Linux virtual machine (VM) in Azure using Azure PowerShell. You can use Azure PowerShell to connect to an Azure subscription and create resources.

Prerequisites

  • Azure Subscription: If you don't have an Azure subscription, create a free account before you begin.
  • Azure PowerShell Module: Install the Azure PowerShell module and connect to your Azure account. For more information, see Install and configure Azure PowerShell.

Sign in to Azure

Open your PowerShell console and run the following command to sign in to your Azure account:

Connect-AzAccount

Follow the prompts to authenticate.

Create a resource group

A resource group is a logical container into which Azure resources are deployed and managed. Create a resource group with the New-AzResourceGroup cmdlet:

New-AzResourceGroup -Name MyResourceGroup -Location eastus

Replace MyResourceGroup and eastus with your desired resource group name and location.

Create a virtual machine

Use the New-AzVM cmdlet to create a virtual machine. This example creates a standard Ubuntu LTS VM. You can specify different images, sizes, and other configurations.

Step 1: Define VM Configuration

$vmConfig = New-AzVMConfig -VMName MyVM -VMSize Standard_DS1_v2
$vmConfig = Set-AzVMSourceImage -VM $vmConfig -PublisherName Canonical -Offer UbuntuServer -Sku 18.04-LTS -Version latest
$vmConfig = Add-AzVMNetworkInterface -VM $vmConfig -Name MyNic -SubnetId $vNetSubnet.Id
$vmConfig = Set-AzVMPassword -VM $vmConfig -Password $myPassword

Note: You'll need to define $myPassword and $vNetSubnet.Id beforehand. Refer to the full script in the Azure documentation for complete setup.

Step 2: Create the VM

New-AzVM -ResourceGroupName MyResourceGroup -Location eastus -VM $vmConfig

This command provisions the VM. It can take a few minutes to complete.

Tip: For more detailed control over VM creation, including advanced networking and storage options, consider using Azure CLI or the Azure Portal. You can also explore different VM sizes and types available in Azure.

Connect to the virtual machine

Once the VM is created, you can connect to it using SSH. First, get the public IP address of the VM:

Get-AzPublicIpAddress -ResourceGroupName MyResourceGroup | Select-Object IpAddress

Then, use SSH to connect:

ssh @

Replace <username> with the username you specified during VM creation and <public_ip_address> with the IP address obtained in the previous step.

Clean up resources

When you are finished with the virtual machine, you can delete the resource group to remove all related resources. This prevents incurring further charges.

Remove-AzResourceGroup -Name MyResourceGroup

Type Y and press Enter to confirm the deletion.

Congratulations! You have successfully created and connected to an Azure virtual machine using PowerShell.