How to add and remove VM’s disk using PowerCLI

Open PowerCLI console and connect to the vCenter where the VM is located. Then, we will retrieve the VM we want to modify and store it is a variable.

#Connect to vCenter
Connect-VIServer -Server  vcenter.example.com
#Get the VM and store it in a variable
$vm = Get-VM MyVM

Lets examine the VM’s hard disks. There are two of them.

Get-HardDisk $vm

CapacityGB      Persistence                                            Filename
----------      -----------                                            --------
36.000          Persistent                           [Datastore] MyVM/MyVM.vmdk
5.000           Persistent                         [Datastore] MyVM/MyVM_1.vmdk

Now, we will add a new disk of size 10 GB.

$vm | New-HardDisk -CapacityGB 10

CapacityGB      Persistence                                            Filename
----------      -----------                                            --------
10.000          Persistent                         [Datastore] MyVM/MyVM_4.vmdk

To reflect the changes to the VM, we need to refresh the variable. Then, we will list the disks again. Notice the new disk we added.

$vm = Get-VM MyVM
Get-HardDisk $vm

CapacityGB      Persistence                                            Filename
----------      -----------                                            --------
36.000          Persistent                           [Datastore] MyVM/MyVM.vmdk
5.000           Persistent                         [Datastore] MyVM/MyVM_1.vmdk
10.000          Persistent                         [Datastore] MyVM/MyVM_4.vmdk

Finally, we will remove the disk we just added.

Get-HardDisk -VM $vm | Where-Object {$_.Filename -like "*MyVM_4*"} | Remove-HardDisk

Verify again

$vm = Get-VM MyVM
Get-HardDisk $vm

CapacityGB      Persistence                                            Filename
----------      -----------                                            --------
36.000          Persistent                           [Datastore] MyVM/MyVM.vmdk
5.000           Persistent                         [Datastore] MyVM/MyVM_1.vmdk
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s