Getting VMWare virtual machine disk space

Comments unfortunately still not fixed but I do have an interesting little script that I put together the other day when I was asked about gathering the total disk space on every virtual server in the fleet.

This uses the VMWare Perl API and you will of course need to put the username/password/vCenter host where appropriate. When run it will display two columns… the “VM-STORAGE” column displays the amount of storage assigned at the VMWare layer and the “OS-STORAGE” will display the total amount visible at the OS layer (as long as VMWare tools are installed). The reason for both is that some servers might not have tools (i.e. appliances) and some may have network storage of some description that you may wish to account for.

So without further ado, the script:

#!/usr/bin/perl -w

$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;
use strict;
use warnings;
use VMware::VIRuntime;
use VMware::VILib;

###SET VMWARE OPTIONS
Opts::set_option('username','');
Opts::set_option('password','');
Opts::set_option('server','');

Opts::parse();
Opts::validate();
Util::connect();

sub round_space {
  my $intValue = shift;

  my @aryStrings = ("B","KB","MB","GB","TB");
  my $intCount = 0;

  while (($intValue > 1024) && ($intCount < 4)) {
    $intValue = $intValue / 1024;
    $intCount = $intCount + 1;
  }

  my $strRoundedNumber = sprintf("%0.2f", $intValue) . $aryStrings[$intCount];

  return $strRoundedNumber;
}

printf "%-11s %-11s %-11sn", "HOSTNAME", "VM-STORAGE", "OS-STORAGE";

foreach my $vmwVM (@{Vim::find_entity_views(view_type => 'VirtualMachine')}) {
  if ($vmwVM->guest->guestState ne "running") {
    next;
  }

  $vmwVM->update_view_data();
  my $strHostName = $vmwVM->name;

  my $vmwStorageInfo = $vmwVM->storage->perDatastoreUsage;
  my $strVMTotalStorage = "";

  foreach(@$vmwStorageInfo) {
    my $intTotalStorage = $_->committed + $_->uncommitted;
    $strVMTotalStorage = round_space($intTotalStorage);
  }

  my $vmwToolsStorageInfo = $vmwVM->guest->disk;
  my $strOSTotalStorage = "";
  my $intOSTotalStorage = 0;

  foreach(@$vmwToolsStorageInfo) {
    $intOSTotalStorage = $intOSTotalStorage + $_->capacity;
  }

  $strOSTotalStorage = round_space($intOSTotalStorage);

  printf "%-11s %-11s %-11sn", $strHostName, $strVMTotalStorage, $strOSTotalStorage;
}

Enjoy!

comments powered by Disqus