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:
1get-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:
1get-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.
1(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:
1((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,
1[math]::Round(((get-vm | Where-object{$_.PowerState -eq "PoweredOn" }).UsedSpaceGB | measure-Object -Sum).Sum)
UPDATE- 21st September 2018
The code above may produce unexpected results when being used in a vSAN environment. The “UsedSpaceGB” figure takes into account the disk in use by FTT scenarios, so if a system has an FTT of 1 the figure reported will be twice the size of the the actual disk files as there is a second copy. This is particularly relevant if the set of VMs being queried spans different storage policies with different protection settings.