iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔖

How to resize the OS disk of an Azure VM

に公開

TL;DR

  • Change the size of an Azure VM's OS disk using Azure PowerShell
  • Take a snapshot before resizing for safety
  • Remembering Invoke-AzVMRunCommand is useful as it allows you to automate operations inside the OS

Introduction

This is a common scenario, but I needed to change the size of an Azure VM's OS disk, so I'm sharing this memo on how I did it with PowerShell.
Just to be safe, I've made sure to take a snapshot of the OS disk before resizing it.
Also, since simply resizing the Azure Disk isn't enough, I use Invoke-AzVMRunCommand to also resize the partition within the OS.

extend-os-disk.ps1
# Set the name of the VM and the name of the resource group as variables
$vmName = "<VM name>"
$resourceGroupName = "<Resource group name>"

# Check the status of the VM
$vm = Get-AzVM -Name $vmName -ResourceGroupName $resourceGroupName -Status

if ($vm.Statuses[1].Code -eq "PowerState/running") {
    Write-Output "The VM is already running."
} else {
    # Retrieve information about the OS disk
    $vm = Get-AzVM -Name $vmName -ResourceGroupName $resourceGroupName
    $osDisk = Get-AzDisk -ResourceGroupName $resourceGroupName -DiskName $vm.StorageProfile.OsDisk.Name

    # Take a snapshot of the OS disk
    $snapshotConfig = New-AzSnapshotConfig -SourceUri $osDisk.Id -Location $osDisk.Location -CreateOption Copy
    $snapshotName = "snap-" + $vmName + "-OSDisk-" + (Get-Date -Format "yyyyMMddHHmmss")
    New-AzSnapshot -Snapshot $snapshotConfig -SnapshotName $snapshotName -ResourceGroupName $resourceGroupName

    Write-Output "Snapshot of the OS disk has been taken."

    # Update the size of the OS disk to 256GB
    $osDisk.DiskSizeGB = 256
    Update-AzDisk -Disk $osDisk -ResourceGroupName $resourceGroupName -DiskName $osDisk.Name

    Write-Output "OS disk size has been updated to 256GB."

    # Start the VM
    Start-AzVM -Name $vmName -ResourceGroupName $resourceGroupName

    Write-Output "The VM has been started."

    # Extend the size of the C drive partition to the maximum available space
    $commandId = "RunPowerShellScript"
    $script = "Resize-Partition -DriveLetter C -Size (Get-PartitionSupportedSize -DriveLetter C).SizeMax"
    Invoke-AzVMRunCommand -ResourceGroupName $resourceGroupName -VMName $vmName -CommandId $commandId -ScriptString $script

    Write-Output "The partition size of the C drive has been extended to the maximum available space."
}

References

  • Invoke-AzVMRunCommand

https://learn.microsoft.com/powershell/module/az.compute/invoke-azvmruncommand?wt.mc_id=MVP_391314

Discussion