Microsoft Azure: Resize Azure VMs using PowerShell

Resizing an Azure Virtual Machine (VM) involves changing the VM’s size to scale it up or down based on your needs. In this article, we’ll show you how to automate Azure VM resizing using PowerShell script. 

Using this best practice approach, we can automate the resizing of Azure VMs without any errors or exceptions. Before we dive into the automation procedure, let’s explore 'What is the best practice for resizing an Azure VM?'

Best Practice for Resizing an Azure VM:

1: Stop the VM

Before resizing, you need to stop the running server. If the VM is currently running, changing its size will cause it to restart.

2: Choose the Right SKU

It’s important to choose the right SKU based on the signals from the VM to determine whether you need more CPU, memory, or storage capacity.

3: Change the VM Size

In the Azure portal, select the virtual machine you want to resize. In the left menu, select size. Pick a new compatible size from the list of available sizes. After picking a size, select Resize.
  • If your VM uses Premium Storage, make sure that you choose an ‘s’ version of the size to get Premium Storage support.
  • Deallocating the VM also releases any dynamic IP addresses assigned to the VM. The OS and data disks are not affected.
  • You can’t resize a VM size that has a local temp disk to a VM size with no local temp disk and vice versa.

4: Start the VM

After the resize finishes, start the VM.

Pre-Checks before Resizing an Azure VM:

Az PowerShell Command to Check the list of supported VM sizes based on location.

Get-AzVMSize -Location "_add_your_preffered_location_"

Example: Get-AzVMSize -Location "East US"

Use this Az PowerShell command to find the current Azure VM size:

Get-AzVMSize -ResourceGroupName "_add_resourceGroup_name_" -Name "_add_your_virtualMachine_name_"

Example: Get-AzVMSize -ResourceGroupName "OpenAI-RG" -Name "OpenAIVM01"

Resize Azure VMs using PowerShell:

PowerShell Automation Script for Resizing Azure Virtual Machines Within a Single Azure Subscription. Before you run the script connect to your Azure subscription using Connect-AzAccount.

########################################################

## Add Subscription Name or Id - #Better to Use Id Always
$Subscription = " "

## Add Azure VMs List seperated by ','

$VMList=@(" "," ") ## Example: @("OpenAIVM01","OpenAIVM02","OpenAIVM03")

## Add New Azure VM Size
$NewAzureSize = " " ## Example: "Standard_D2ds_v4"

########################################################

Set-AzContext -Subscription "$Subscription"
$RGs = Get-AzResourceGroup
foreach ($RG in $RGs)
{
    $VMs = Get-AzVM -ResourceGroupName $RG.ResourceGroupName
    foreach ($VM in $VMs)
    {
        $VMName = $VM.Name
        $ResourceGroupName = $VM.ResourceGroupName
        $Location = $VM.Location
        $OSType = $VM.StorageProfile.OSDisk.OSType

        if ($VMList -contains $VMName)
        {
            Write-Output ("------------------------------------------------------------")
            Write-Output ("Virtual Machine: $VMName")
            Write-Output ("ResourceGroup  : $ResourceGroupName")
            Write-Output ("Location   : $Location")
            Write-Output ("OSType : $OSType `n")
            Write-Output ("Deallocating $VMName VM.")
            Stop-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -Force
            Write-Output ( "$VMName VM Stopped. `n")
            Write-Output ("Updating $VMName VMSize.")
            $vm = Get-AzVM -ResourceGroupName $ResourceGroupName -VMName $VMName
            $vm.HardwareProfile.VmSize = $NewAzureSize
            Update-AzVM -VM $vm -ResourceGroupName $ResourceGroupName
            Write-Output ( "Successfully resized $VMName VM to size $AzureSize. `n")
            Write-Output ("Starting $VMName VM")
            Start-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName
            Write-Output ("$VMName VM Started.")
            Write-Output ("-------------------------------------------------------------")
        }
    }
} 

Sample Output:

Resize Azure VM PowerShell

An Advanced PowerShell script that resizes an Azure VM using Try and Catch blocks

Here's an advanced PowerShell script that resizes an Azure VM using Try and Catch blocks to handle potential errors:

# Define variables
$SubscriptionId = "add_subscription_id"
$VMsList = @("WINOPENAIVM01", "WINOPENAIVM02", "WINOPENAIVM03") #Provide your VM List that need to be Resized
$NewAzureSize = "Standard_D4as_v5" #Provide your New Azure VM Size

Set-AzContext -Subscription $SubscriptionId

$AzVMs = Get-AzVM | Select-Object -Property Name, ResourceGroupName, Location

foreach ($VM in $AzVMs)
{
   $VMName = $VM.Name
   $ResourceGroupName = $VM.ResourceGroupName
   $Type = $VM.Type
   $Location = $VM.Location
   $ProvisioningState = $VM.ProvisioningState

    if ($VMsList -contains $VMName)
    {
        Write-Host "********************************************************************"
        # Get the VM object
        try {
            $azvm = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName
            Write-Host "VM $VMName found in resource group $ResourceGroupName in $Location."
        } catch {
            Write-Error "Error retrieving VM: $($_.Exception.Message)"
            Exit -1
        }

        Write-Host "Virtual Machine: $VMName"
        Write-Host "ResourceGroup  : $ResourceGroupName"
        Write-Host "Location   : $Location"
        Write-Host "--------------------------------------------------------------------"

        # Check if desired size is available
        try {
            $availableSizes = Get-AzVMSize -Location $Location
            if ($availableSizes.Name -contains $NewAzureSize) {
                Write-Host "VM size $NewAzureSize is available."
            } else {
                Write-Error "VM size $NewAzureSizeis not available in region $Location."
                Exit -1
            }
        } catch {
            Write-Error "Error checking available sizes: $($_.Exception.Message)"
            Exit -1
        }

        Write-Host "--------------------------------------------------------------------"
        Write-Host "Deallocating $VMName VM."
        Stop-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -Force
        Write-Host "$VMName VM Stopped."
        Write-Host "--------------------------------------------------------------------"

        # Update VM size
        try {
            $vm = Get-AzVM -ResourceGroupName $ResourceGroupName -VMName $VMName
            $vm.HardwareProfile.VmSize = $NewAzureSize
            Write-Output ("Updating $VMName VMSize.")
            Update-AzVM -VM $vm -ResourceGroupName $ResourceGroupName
            Write-Host "VM $VMName resized to $NewAzureSize successfully."
        } catch {
            Write-Error "Error resizing VM: $($_.Exception.Message)"
            Exit -1
        }

        Write-Host "--------------------------------------------------------------------"
        Write-Host "Starting $VMName VM"
        Start-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName
        Write-Host "$VMName VM Started."
        Write-Host "********************************************************************"
    }
}

Code Explanation:

Define variables: Replace the placeholders with your actual resource group name, VM name, and desired new size.

Get VM object: Attempts to retrieve the VM using Get-AzVM.

  1. Try block: If successful, displays a message indicating the VM was found.
  2. Catch block: Handles any errors during retrieval and exits the script with an error message.

Check available size: Tries to retrieve a list of available VM sizes in the same region using Get-AzVMSize.

  • Try block: If successful, checks if the desired size is present.
  • If present, displays a message confirming availability.
  • If not present, exits the script with an error message.
  • Catch block: Handles any errors during size checking and exits the script with an error message.

Update VM size: Attempts to update the VM size using Set-AzVM.

  • Try block: If successful, displays a message confirming the VM was resized.
  • Catch block: Handles any errors during resizing and exits the script with an error message.

Related Blog Articles:

👉 Find Azure VM Creation Date and Time
👉 Find Azure VM Username and Password

Microsoft References: