Using VMware PowerCLI 5 to check for Snapshots

Using VMware PowerCLI 5 to check for Snapshots

We recently integrated BackupExec for one of our existing clients, however, after getting woken up at 4am this past weekend, we found out that a snapshot filled up the LUN for a VM. We finally determined it was from BackupExec hanging! After restarting the service, we were able to fix it easily by doing a dynamic LUN expansion on the client’s EVA 4400. After we did that, we were able to commit the snapshot with the added free space. We wanted to ensure this didn’t happen again, so after doing some research, we decided to implement a custom PowerShell script. This script would connect to the vSphere host, get all the VMs, check each one for a snapshot, and if any were found to dispatch an email to us. Here’s the script, enjoy!

check_snapshots.ps1:

$client="myorganization"
$viserver="myvcenterfqdn"
$viuser="myusername"
$vipass="mypassword"

$from="from@email.com"
$to="to@email.com"
$smtp_host="mysmtp.relay.com"

# DO NOT EDIT ANYTHING BELOW THIS LINE

Add-PSSnapin VMware.VimAutomation.Core
connect-viserver -server $viserver -protocol https -user $viuser -password $vipass

$found_error=0
$error_count=0
$body="The following Virtual Machine(s) contain a Snapshot:`n"
$body2="Entire Log:`n"

$virtual_machines=Get-VM
foreach ($virtual_machine in $virtual_machines) {
	$snapshot=Get-Snapshot -VM $virtual_machine
	
	if ($snapshot) {
		$found_error=1
	        $error_count++

		Write-Host $virtual_machine.Name ": Snapshot found!"
		$body+="`t"+ $virtual_machine.Name +": Snapshot found! Snapshot name: "+ $snapshot.Name +"`n"
		$body2+="`t"+ $virtual_machine.Name +": Snapshot found! Snapshot name: "+ $snapshot.Name +"`n"
	} else {
		Write-Host $virtual_machine.Name ": Snapshot not found."
	        $body2+="`t"+ $virtual_machine.Name +": Snapshot not found.`n"
	}
}

if ($found_error) {
    $subject=$client +": "+ $error_count +" Snapshot(s) found!"
    $smtp = new-object System.Net.Mail.SmtpClient($smtp_host)
    $message = New-Object System.Net.Mail.MailMessage "${from}", "${to}", "${subject}", "${body}`n${body2}"
    $smtp.Send($message)
}

You need the VMware PowerCLI which can be found here.

Lastly, if you wanted to execute this from Scheduled Tasks, you could use a bat file like so:

C:WINDOWSsystem32WindowsPowerShellv1.0powershell.exe -file "C:check_snapshots.ps1"