Tuesday, April 18, 2017

VMware Snapshot Auto Delete Powershell Script

This script will look through vcenter for snapshots that have a specific description. If description matches criteria, then snapshot will be deleted and notification sent based on contents of snapshot description. Requires VMware snapin/module

# Script to auto delete vmware snapshots based on text in snap description
# Dan Dill, 2017

# variables here
$date = get-date -format MM/dd/yyyy
$dateregex = "(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}"
$emailregex = '\w+\.\w+@\w+\.\w+'
$vcenterserver = 'vcenterserver.domain'
$emaildomain = '*@domain.com*'
$mailserver = 'mailserver.domain'
$from = "Vmware Robot "

# Load PowerCli
# Load VMware Snapin or Module (if not already loaded)  
if (!(Get-Module -Name VMware.VimAutomation.Core) -and (Get-Module -ListAvailable -Name VMware.VimAutomation.Core)) {  
    Write-Output "loading the VMware COre Module..."  
    if (!(Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) {  
        # Error out if loading fails  
        Write-Error "`nERROR: Cannot load the VMware Module. Is the PowerCLI installed?"  

#connect to vcenter and grab snaps with description that contains 'AutoDelete' or 'Auto Delete'
connect-viserver $vcenterserver
$snaps = get-vm | get-snapshot | where {$_.description -like '*AutoDelete*' -or $_.description -like '*Auto Delete*'}

#main loop of script, executes for each snapshot found
foreach ($snap in $snaps){
 # grab date in snap in format mm/dd/yyyy
 $snapdate = [datetime](select-string -inputobject $snap.description -pattern $dateregex | Select -First 1).matches.value
 $snaplist = $snap | select name,description,created,VM | fl | out-string
 # if the snapshot description date matches today then act upon it
 if ($snapdate -eq $date){
  # if the description has an email domain match then send out a notification email
  if ($snap.description -like $emaildomain){
   $emails = (Select-String -InputObject $snap.description -Pattern $emailregex).matches
    foreach ($email in $emails){
    send-mailmessage -from $from -to $email -subject "Snapshot Deletion" -body "Hello, the system is deleting the following snapshot $snaplist " -smtpServer $mailserver
   # delete the snapshot
   $snap | Remove-Snapshot -confirm:$false
   clear-variable snaplist
   # wait 60 seconds just to be nice to the storage system
   start-sleep -s 60

No comments: