PowerCLI: Get-VMSize

James Young · April 26, 2011

I’m employed as a server admin, with most of my time spent working with VMware and managing a reasonably sized fleet of machines.  As such, I have a range of various Powershell scripts I’ve written to take advantage of VMware’s PowerCLI interface for Powershell.  PowerCLI is, in a word, great.  It provides some pretty good in-depth insight to what’s going on in vCenter, and since it ties into Powershell, it’s easy to script up whatever you want to do.

Anyhow, below is a filter script, which was cobbled together from some code from a source I can’t recall (if you know the original source, let me know so I can attribute it properly!).  The purpose of this script is to take a bunch of VMs, calculate the Size and Used disk space of those VMs, and dump that out.

Begin {</p>

}

Process {
    $vm = $_

    $report = $vm | select Name, Id, Size, Used
    $report.Size = 0
    $report.Used = 0

    $vmview = $vm | Get-View
    foreach($disk in $vmview.Storage.PerDatastoreUsage){
           $dsview = (Get-View $disk.Datastore)
        #$dsview.RefreshDatastoreStorageInfo()
        $report.Size += (($disk.Committed+$disk.Uncommitted)/1024/1024/1024)
        $report.Used += (($disk.Committed)/1024/1024/1024)
    }

    $report.Size = [Math]::Round($report.Size, 2)
    $report.Used = [Math]::Round($report.Used, 2)

    Write-Output $report
}

End {

}</span>

</blockquote>

 An example of its use follows;

Get-VM | .\Get-VMSize.ps1 | Measure-Object -Property Size -Sum

The input should be a VMware.VimAutomation.ViCore,Impl.V1.Inventory.VirtualMachineImpl object, such as what gets returned by Get-VM.  Each output object from the script will contain the following fields;

  • Name - The text name of the VM as given by the Name field in the input object.
  • Id - The ID of the VM as given by the Id field of the input object.
  • Size - The sum of the sizes of all disks used by the VM.  This size is the figure set when provisioning the disk, not the actual on-disk allocation (ie, it will be bigger than the disk use if you are using thin provisioning).
  • Used - The amount of actual disk space being used by all disks on the VM.  This size is smaller than Size if the VM is thin provisioned.

Enjoy.

Twitter, Facebook