VMware PowerCLI script to list snapshots older than specific days

A VMware vSphere PowerCLI script to find and email a list of all VMware guests that have snapshot older than 3 days.

# List all VM with snapshots
# Run as scheduled task with a user with rights to view all VMs

Add-PSSnapin VMware.VimAutomation.Core

$Age = 3
$strOutFile = “c:\snapshot-result.htm”
del $strOutFile

# HTML/CSS style for the output file
$head = “

# SMTP info
$smtpServer = “my.smtp.com”
$strFrom = “vcenter1”
$strTo = “email1@mymail.com, email2@mymail.com”
$strSubject = “Snapshot older than 3 days – ” + (get-date -DisplayHint date)
$strBody = “Attached is the list of Snapshots”
$strMail = “<-H2>” + $strSubject + “<-/H2>”
#Remove the – in the above line

# List your vCenter servers in quotes separated by commas
$Servers=”vcenter1″,”vcenter2″
foreach ($Server in $Servers){
Connect-VIServer $Server
$date=Get-Date -uFormat “%Y%m%d%H%M%S”
$strSubject = “INV Snapshots older than 3 days – ” + (get-date -DisplayHint date)

# Get the list of VM’s
$myCol = get-vm | get-snapshot | select vm, Created, name, Description, SizeMB, SizeGB, @{N=”DaysOld”; E={((Get-Date) – $_.Created).Days}} | ? {$_.DaysOld -gt $Age}

# Write the output to an HTML file
if ($myCol -ne $null){
$myCol | Sort-Object VM | ConvertTo-HTML -Head $head -Body $Server | out-File $strOutFile -Append
Clear-Variable myCol
}

DisConnect-VIServer -Server * -Force -Confirm:$false

}

if (Test-Path $strOutFile){
# Mail the output file
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($strOutFile)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $strFrom
$msg.To.Add($strTo)
$msg.Subject = $strSubject
$msg.IsBodyHtml = 1
$msg.Body = Get-Content $strOutFile
# $msg.Attachments.Add($att)
$smtp.Send($msg)
}

ELSE {
# Mail the output file
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $strFrom
$msg.To.Add($strTo)
$msg.Subject = “Snpshot Older Than 3 Days”
$msg.IsBodyHtml = 1
$msg.Body = “Great news :) There are no snapshot older than 3 days”
$smtp.Send($msg)
}