vSphere snapshot overview script (with e-mail report)

I was looking for a way to e-mail an overview of all exisiting snapshots (on virtual machines) in our virtual environment.
VMware provides an excellent powershell cmdlet pack (known as PowerCLI), you can download the latest version (as of today) here: http://blogs.vmware.com/vipowershell/2009/11/powercli-40-u1-is-out.html

I used PowerCLI to write a script that does the following:

  • Loop through all virtual machines to check if there a snapshots created for a specific virtual machine;
  • sum up all of the snapshots for a machine containing snapshots;
  • e-mail a report of the above.

Here is the script:

Add-PSSnapin -Name "VMware.VimAutomation.Core"

$VIServer = "yourvirtualcenterserver.test.local"
$VIUsername = "DOMAIN\username"
$VIPassword = "password"

Connect-VIServer -Server $VIServer -User $VIUsername -Password $VIPassword

$AllVirtualMachines = Get-VM

$SmtpClient = new-object system.net.mail.smtpClient 
$MailMessage = New-Object system.net.mail.mailmessage 

$SmtpClient.Host = "smtpserver.test.local" 
$MailMessage.from = "notification@smtpserver.test.local" 
$MailMessage.Headers.Add("message-id", "<3BD50098E401463AA228377848493927-1>")
$MailMessage.IsBodyHtml = 1

$MailMessage.Subject = "VMware snapshot overview"
$MailMessage.Body += "<FONT FACE='Arial, Helvetica, Geneva'><h2>VMware snapshot overview:</h2><br>"

foreach ($VirtualMachine in $AllVirtualMachines)
	$AllSnapshots=Get-Snapshot -VM $VirtualMachine
	if ($AllSnapshots.count -gt 0)
		$MailMessage.Body += "<b>" + $VirtualMachine + "</b><br>"
		foreach ($Snapshot in $AllSnapshots)
			If ($Snapshot.ID -like "VirtualMachineSnapshot-*")
				$MailMessage.Body += $Snapshot.Created, $Snapshot.Name, $Snapshot.Description + "<br>"
		$MailMessage.Body += "<br>"
$MailMessage.Body += "</font>"