Using PowerCLI to measure VM disk space usage.

I had a recent need to calculate how much disk space was being taken up by all the VMs in my vSphere environment for capacity planning purposes. PowerCLI is an ideal tool for working this out, and this is how I went about it.

First, we need to get a list of the Powered-On virtual machines- for my calculations I wasn’t worried about those powered-off VMs used as backups or tests. This can be accomplished with the following line of PowerCLI:

get-vm | Where-object{$_.PowerState -eq "PoweredOn" }

This line retrieves all of the VMs from the vSphere system and filters to just the Powered On servers. Next, we need to work out how much space the hard disks take up. There’s a command “Get-HardDisk” which looks useful, this returns a list of the hard drives connected to these VMs:

get-vm | Where-object{$_.PowerState -eq "PoweredOn" } | Get-HardDisk

And then we can use “Measure-Object” to report on the capacities of these disks and add them together.

(get-vm | Where-object{$_.PowerState -eq "PoweredOn" } | Get-HardDisk | measure-Object CapacityGB -Sum).sum

This returns a number, in gigabytes, of the total size of all the disks of the powered-on VMs on this vCenter. However, most of my VMs are thin-provisioned, so how much space am I actually consuming? Get-HardDisk can’t tell me this, but the “UsedSpaceGB” property of the VM can. The new code looks like this:

((get-vm | Where-object{$_.PowerState -eq "PoweredOn" }).UsedSpaceGB | Measure-Object -Sum).Sum

This produces a number, again in gigabytes, of the total size taken up by all these disks. Just what I needed, except the resulting number includes a lot of decimal places. Last step is to neaten this up by rounding it to the nearest Gigabyte,

[math]::Round(((get-vm | Where-object{$_.PowerState -eq "PoweredOn" }).UsedSpaceGB | measure-Object -Sum).Sum)


Leave a Reply

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