Adding Data Disk To Azure VM Using PowerShell

Learn about different ways of adding data disk to Azure VM

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

This article is a hands-on on how to add data disk using Powershell on Azure virtual machine and please remember this is an additional resource and you might have to pay for it. I have already explained how to create and attach data disks using the Azure portal here in this article.[ So in this article, we are going to try another and simple way to do it.

So at first let us create and initialize some variables that we will use for creating data disk.

So first is the resource group and my resource group name is anish-grp so this variable holds the anish-grp.

$resourcegroup = 'anish-grp'

This variable holds the location of the machine. So currently demovm is in the East US location so I have given my location as East US.

$location = 'East US'

The next one is the disk type and I'm adding a standard disk. So this variable holds the disk type. I am using a standard disk because of pricing factors.

$storageType = 'Standard_LRS'

The next one is the diskname that we want to be created. This variable holds the diskname that is demodatadisk and the next one holds the size of the disk.

$dataDiskName = 'demodatadisk'  
$dataDiskSize = 20

So after initializing the disks, now we need to execute some more commands to create the data disk. So let's execute the next command.

So now we need to create a new disk configuration and below is the command to do that and we are using the variables we have initialized.

$datadiskConfig = New-AzDiskConfig -SkuName $storageType -Location $location -CreateOption Empty -DiskSizeGB $dataDiskSize

After creating the configuration now are we are going to create a new disk.

$dataDisk01 = New-AzDisk -DiskName $dataDiskName -Disk

Now we need to get a reference of a virtual machine on which we are going to attach the disk. So we're going to get a reference to the virtual machine and that is demovm.

$datadiskConfig -ResourceGroupName $resourcegroup

Now we are going to add a data disk to the virtual machine and below is the command for that. I have assing LUN to 1 because when I created the data disk and attached the disk in this article, the LUN was 0 for this disk it is going to be 1.

$vm = Add-AzVMDataDisk -VM $vm -Name $dataDiskName -CreateOption Attach -ManagedDiskId $dataDisk01.Id -Lun 1

After this command, we need to update the virtual machine, and below is the command to do that. So let us update the virtual machine.

Update-AzVM -VM $vm -ResourceGroupName $resourcegroup

Now, if you go to all resources and check for the disk, you must find the newly created disk there.

If you want to learn more then please have a look at this documentation.

In this article, we saw how to create and attach data disks to Azure virtual machine using PowerShell and how easy it is.

Thanks for reading.

No Comments Yet