Expanding the Virtual machine hard disk is most common administration task for VMware(or Hyper-V) administrator. The general process is connecting to virtual center console, locate the VM, go to properties, identify the hard disk for which you want to increase the space and enter new hard disk size in the “Provisioned Size” box and click OK. This complete the task. For example, you have 10 such VMs on which you have to increase the space, then repeating the above steps for all VMs is a cumbersome task. So, let us see how we can easily do it with powershell.
Today I got a requirement to expand a VM hard disk. Since I am exploring VMware PowerCLI these days, I thought of using PowerShell for this operation to see how quickly I can do this. Once I figureout the cmdlet to use, I felt it is too easy.
Here is the one liner I used to expand hard disk 1 in a VM.
Get-VM VMServer1 | Get-HardDisk | ? {$_.name -eq "Hard disk 1" } | Set-HardDisk -CapacityKB 52428800
You need to execute this from VMware PowerShell CLI where Get-VM, Get-Harddisk cmdlets are available. Also before executing the above, you need to ensure that you already established a connect to Virtual Center Server from your powershell window. You can do it by simply running “Connect-VIServer -Server VCSERVER1” where VCSERVER1 is the name of the virtual center server.
In this one liner, I am using Get-VM to get a virtual machine reference for which I want to increase the space and using Get-Harddisk cmdlet to read the disks information of the returned VM. From there I am filtering out the disks for which I want to expand the space. Since I am just interested in expanding “Hard disk 1”, I created a where-object to filter the disks with the given name. And finally expanding the disk by using set-HardDisk cmdlet which takes the target size in KBs.
From my readings, I understood that, Set-Harddisk also expands the disk in guest OS provided you are passing the credentials to it. I did that for a VM which is running windows 2003 but it didn’t work. May be this is applicable only to Windows 7/2008 computers which are having in-built GUI option to extend the hard disks from disk management. No need to use disk part tool in that case. If it is a windows 2003/XP guest OS, then you should use diskpart tool to expand it.
Hope this information helps…