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
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.Subject = $strSubject
$msg.IsBodyHtml = 1
$msg.Body = Get-Content $strOutFile
# $msg.Attachments.Add($att)

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

About Andrew Lin

Hi, I have always wanted to creat a blog site but never had the time. I have been working in Information Technology for over 15 years. I specialize mainly in networks and server technologies and dabble a little with the programming aspects. Andrew Lin

View all posts by Andrew Lin →