This is a PowerShell script that will connect to a Vcenter instance and print out a report of the snapshots it has found. The report can be written to the screen, a file or emailed.
Why this is important
Snapshots are a wonderful thing if used properly. Snapshots produces a delta file of a static moment in time. VMware recommends strongly that they be kept no more than 3 days, much less if the VM is very active. Snapshots kept longer will slow down the VM and make deleting the snapshot very disk intensive. In some not so extreme cases, a snapshot may not be deleted and the VM may become unrecoverable and crash.
Script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#source: https://stackoverflow.com/questions/73548103/powershell-script-to-check-for-vm-snapshots-and-send-email-report
#Variables
$vCenter = "something" $IP or FQDN
$vCenterUser = "vsphere.local\administrator"
$vCenterPass = "password"
#HTML
$style = @'
<style>
body {font-family: Arial; font-size: 10pt;}
table {border: 1px solid red; border-collapse: collapse;}
th {border: 1px solid; background-color: #4CAF50; color: white; padding: 5px;}
td {border: 1px solid; padding: 5px;}
</style>
'@
#Connect to vCenter"
Write-Host "Connecting to $vCenter"
Connect-VIServer -Server $vCenter -User $vCenterUser -Password $vCenterPass -Force | Out-Null
Write-Host " Connected to $vCenter"
# Generate snapshot report
$SnapshotReport = Get-Vm | Get-Snapshot | Select-Object VM,Created,Description,PowerState,SizeMB |
Sort-Object SizeMB
# Round SizeMB because it is too long normally
$SnapshotReport.SizeMB = [math]::Round($SnapshotReport.SizeMB,2)
# Convert report to HTML
$SnapshotReportHTML = $SnapshotReport | ConvertTo-Html -Head $style | Out-String
# Write to screen
Write-Host ($SnapshotReport | Format-Table | Out-String)
# Write HTML report to a file
#$SnapshotReportHTML | Out-File -FilePath file.html
# -------------------------------------------------------------------
# Commenting the following out as every email server is different.
<#
#Sending email report
Write-Host "Sending VM snapshot report"
# code is nicer/better maintainable if you use splatting
$params = @{
SmtpServer = "smtp.gmail.com"
Port = "587"
From = "email_address"
To = "email_address"
Subject = "Snapshot Email Report for $Date"
Body = $SnapshotReportHTML
BodyAsHtml = $true
# more parameters can go here
}
$mycredentials = Get-Credential
Send-MailMessage @params -UseSsl -Credential $mycredentials
#>
# -------------------------------------------------------------------
Write-Host " Completed"