Quick and Dirty Scripting

A blog that focuses on automating system administration tasks for Linux, Windows, and VMware ESX

Monday, November 5, 2007

 

PowerShell and VMware Managment

I know that I just blogged yesterday about sending emails with PowerShell, BASH, and VBScript, but I got a chance today to install VMware's PSSnapin for Powershell. From the looks of this beta, its going to be a very powerful product that almost anyone can write scripts for. What an example.

I wrote a script in Perl using VMware's Perl SDK to display any VM Snapshot that a supplied VirtualCenter knows about. The code to do this in Perl is as follows:

use strict;
use warnings;
use Getopt::Long;
use VMware::VIRuntime;
use Term::ReadKey;

my %opts = (server => undef, username => undef,);

GetOptions (\%opts,"server=s", "username=s");

if( !defined ($opts{server} && $opts{username}) ) {
help();
exit (1);
}

ReadMode('noecho');
print "Enter $opts{username}\'s password: ";
my $password = ReadLine(0);
chomp $password;
ReadMode('normal');

# login
my $url = "https://" . $opts{server}. "/sdk/vimService";
Vim::login(service_url => $url, user_name => $opts{username}, password => $password);

# get VirtualMachine views for all powered on VM's
my $vm_views = Vim::find_entity_views(view_type => 'VirtualMachine');

# snapshot each VM
my $i;
foreach (@$vm_views) {
if( defined $_->snapshot ) {
print "-------------------------------------------------------------\n";
print $_->name . " has at least one snapshot defined . . . \n";
foreach $i (0 .. $#{$_->snapshot->rootSnapshotList} ) {
print "\t" . $_->snapshot->rootSnapshotList->[$i]->name . " @ " . $_->snapshot->rootSnapshotList->[$i]->createTime . "\n";
}
print "-------------------------------------------------------------\n";
}
}

# logout
Vim::logout();

sub help {
my $help_text = <<'END'; USAGE: query_snapshot.pl --server --user

Example:
query_snapshot.pl --server vc1 --user administrator

END
print $help_text;
}

Now using Powershell and the VMware Snapin:

Add-PSSnapin VMware.VimAutomation.Core
Get-VIServer vc1.example.com
Get-VM | % { $_.Name; Get-Snapshots $_ }

That's it. Everything is provided for you like Authentication, handling XML returned by VirutalCenter's Web Services, etc . . . The Perl SDK is very powerful as well, but you have to do a lot more coding to get things done. With the PowerShell snapin, the script is all of three lines. Now the snapin is only in beta testing right now so things can change in the future.

Labels: ,


Comments: Post a Comment





<< Home

Archives

October 2007   November 2007   December 2007   January 2008   February 2008   April 2008   October 2009  

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]