Filename information of a VM snapshot for ESX server

exsnpfilename.pl

Copyright © 2008 VMware, Inc. All rights reserved.

#!/usr/bin/perl -w
#
# Copyright 2008 VMware, Inc.  All rights reserved.
#######################################################################################
# DISCLAIMER. THIS SCRIPT IS PROVIDED TO YOU "AS IS" WITHOUT WARRANTIES OR CONDITIONS 
# OF ANY KIND, WHETHER ORAL OR WRITTEN, EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY 
# DISCLAIMS ANY IMPLIED WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY 
# QUALITY, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. 
#######################################################################################

use VMware::VIM2Runtime;
use VMware::VILib;
use VMware::VMUtil;

sub create_hash;
sub get_vm_info;
sub print_log;

#######################################################################################
#
# exsnpfilename.pl
#	Example script to get filename property of the snapshot object for a given VM 
#	Parameters:
#		-- vmname 			Virtual Machine name
#		-- out 				Output file name

# This script works with VMware ESX Server 3.0 or later.
#######################################################################################

my %opts = (
   'vmname' => {
      type => "=s",
      help => "The name of the virtual machine",
	  variable => "vmname",
      required => 1,
   },
   'out'=>{
      type => "=s",
      help => "The file name for storing the script output",
	  variable => "out",
      required => 0,
   },
);

# validate options, and connect to the server
Opts::add_options(%opts);
Opts::parse();
Opts::validate(\&validate);

my @valid_properties;


Util::connect();
get_vm_info();

# logout
Util::disconnect();

# This subroutine create the log file or print the output on console.
# ===================================================================
sub get_vm_info {
 
   my $vmname = Opts::get_option ('vmname');
   my $filename = Opts::get_option('out');

####################################################################################
#	Find the virtual machine
####################################################################################
   my $vm_view  = Vim::find_entity_view (view_type => 'VirtualMachine', filter =>{ 'name'=> $vmname});

####################################################################################
#	Creation of output file or display output on console
####################################################################################
   if ($vm_view) {
      if (defined (Opts::get_option('out'))) {
          $filename = Opts::get_option('out');
         my $extension = lc substr($filename, length($filename)-4, 4);
         if($extension ne '.xml') {
            $filename =$filename.'.xml';
         }
      }

      if (defined (Opts::get_option('out'))) {
         print OUTFILE "\n";
      }
      else {
         Util::trace(0,"\nInformation of Virtual Machine ". $vm_view->name." \n\n");
      }

####################################################################################
#	Printing the output - filename and virtual machine name
####################################################################################
	  foreach (@valid_properties) {
         if ($_ eq 'vmname') {
            if (defined ($vm_view->config->name)) {
               print_log($vm_view->config->name,"Name","Name");
			 
            }
            else {
               print_log("Not Known","Name","Name");
            }
         }
         elsif($_ eq 'fileName') {
			 if (defined ($vm_view->snapshot->currentSnapshot)) {
			    my $snp_view = Vim::get_view (mo_ref => $vm_view->snapshot->currentSnapshot);
				my @arrdeviceInfo = @{$snp_view->config->hardware->device};
				foreach (@arrdeviceInfo) {
				   my $device_Info = $_; 
				   if (defined ($device_Info->backing)) {
				      print_log($device_Info->backing->fileName,"fileName","FileName");
				   }
			    }	  
			 }           
			 else {
               print_log("Not Known","fileName","File Name");
             }
          }
        
       }
       if (defined (Opts::get_option('out'))) {
          print OUTFILE  "\n";
       }


    if (defined (Opts::get_option('out'))) {
       print OUTFILE  "\n";
    }
  }
}

# This subroutine create the log file or print the output on console.
# ===================================================================
sub print_log {
   my ($propvalue, $xmlprop, $prop) = @_;
   if (defined (Opts::get_option('out'))) {
      print OUTFILE  "<".$xmlprop.">" . $propvalue
                     ."\n";
   }
   else {
      Util::trace(0, $prop.":\t\t ".$propvalue." \n");
   }
}


# validate the host's fields to be displayed
# ===========================================
sub validate {
   my $valid = 1;
   my @properties_to_add;
   my $length =0;

   @valid_properties = ("vmname",
                           "fileName",
                          );

   if (Opts::option_is_set('out')) {
     my $filename = Opts::get_option('out');
     if ((length($filename) == 0)) {
        Util::trace(0, "\n'$filename' Not Valid:\n$@\n");
        $valid = 0;
     }
     else {
        open(OUTFILE, ">$filename");
        if ((length($filename) == 0) ||
          !(-e $filename && -r $filename && -T $filename)) {
           Util::trace(0, "\n'$filename' Not Valid:\n$@\n");
           $valid = 0;
        }
        else {
           print OUTFILE  "\n";
        }
     }
  }
  return $valid;   
}

The sample code is provided "AS-IS" for use, modification, and redistribution in source and binary forms, provided that the copyright notice and this following list of conditions are retained and/or reproduced in your distribution. To the maximum extent permitted by law, VMware, Inc., its subsidiaries and affiliates hereby disclaim all express, implied and/or statutory warranties, including duties or conditions of merchantability, fitness for a particular purpose, and non-infringement of intellectual property rights. IN NO EVENT WILL VMWARE, ITS SUBSIDIARIES OR AFFILIATES BE LIABLE TO ANY OTHER PARTY FOR THE COST OF PROCURING SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOSS OF USE, LOSS OF DATA, OR ANY INCIDENTAL, CONSEQUENTIAL, DIRECT, INDIRECT, OR SPECIAL DAMAGES, ARISING OUT OF THIS OR ANY OTHER AGREEMENT RELATING TO THE SAMPLE CODE.

You agree to defend, indemnify and hold harmless VMware, and any of its directors, officers, employees, agents, affiliates, or subsidiaries from and against all losses, damages, costs and liabilities arising from your use, modification and distribution of the sample code.

VMware does not certify or endorse your use of the sample code, nor is any support or other service provided in connection with the sample code.