Azure PowerShell: Attach New Data Disk to Existing VM

Here’s a script that attaches a new data disk to an existing VM in Azure. It determines the appropriate LUN based on the existing data disks associated to the VM.

$ResourceGroupName = "MyResourceGRoup"
$StorageAccountName = "mysstorageaccount"
$VmName = "vm01"
$DiskSizeInGB = 512
 
$Vm = Get-AzureRmVM -ResourceGroupName $ResourceGroupName -Name $VmName
$MaxLun = 0
$VmDataDisks = $vm.StorageProfile.DataDisks
ForEach ($VmDataDisk in $VmDataDisks)
{
  $VmDataDiskLun = $VmDataDisk.Lun
  If ($VmDataDiskLun -gt $MaxLun)
  {
    $MaxLun = $VmDataDiskLun
  }
}
$Lun = $MaxLun + 1
 
$DiskName = "Data0" + ($Lun + 1).ToString()
$VhdUri = "https://" + $StorageAccountName + ".blob.core.windows.net/vhds/" + $VmName + $DiskName + "Disk.vhd"
 
$Vm = Add-AzureRmVMDataDisk -VM $Vm -Name $DiskName -CreateOption Empty -Caching None -Lun $Lun -DiskSizeInGB $DiskSizeInGB -VhdUri $VhdUri
Update-AzureRmVM -VM $Vm -ResourceGroupName $ResourceGroupName

Hope this helps!

This entry was posted in Azure, PowerShell. Bookmark the permalink.

Leave a Reply

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