...hopefully some useful VMware related stuff

Removing Snapshots older than X days

27/10/2009 11:07

The script below queries virtualcenter for all snapshots and then checks if each one is older than the amount of days you specify in the command line.

Download Here

If they are older you get a confirmation as to whether to remove or not. Then it moves on to the next snapshot or ends if the last one.

 

# Dans Snapshot Remover
# snapremdate.ps1
# 20091027
# Version 1.5
# https://www.a2-alpha.co.uk
#
# Usage:
# At the Powershell commandline type ./snapremdate.ps1 30
# This will run the script from your current location attach to your vc
# And query the snapshots, if older than 30 days (or whatever you put above)
# It will ask for confirmation of removal by default but just remove the -Confirm switch
# when happy with it.
#
# Sets up VI snapins for powershell

Add-PSsnapin VMware.VimAutomation.Core
Initialize-VIToolkitEnvironment.ps1

# Starts connection to a VC Server

$vcserver = "vCenter"
connect-VIServer $vcserver
clear


# Title for page

""
"********************"
"* Snapshot Remover *"
"*  a2-alpha.co.uk  *"
"********************"
""

#Lists current open snapshots

$snap = get-vm | get-snapshot
$snap | select vm, name, created, description

#setup date variables
#current date
$cdate = get-date

#age to query (days) just for testing but the $dage could be manually set rather than through an argument on the cmdline.
#$ddage = -30

$dage = -$args[0]
$dagen = -$dage

#target date (the current date minus however many days were inputed in the command line)
$tdate = $cdate.adddays($dage)

#query date (will be from snaplist) this is just for testing
#$qdate = $cdate.adddays(-29)


# Starts going through each snapshot, then queries if older than X days and then waits for confirmation of removal

$AllVirtualMachines = Get-VM

foreach ($VirtualMachine in $AllVirtualMachines)

{$AllSnapshots=Get-Snapshot -VM $VirtualMachine
echo ""
foreach ($Snapshot in $AllSnapshots)

 {If ($Snapshot.ID -like "VirtualMachineSnapshot-*")

  {Write-Host $VirtualMachine.Name, $Snapshot.Name, $Snapshot.Description, $Snapshot.Created

If($Snapshot.Created -lt $tdate)
{
""
"The Snapshot $snapshot is older than $dagen day(s) and will be removed"
""
   Remove-Snapshot -snapshot $Snapshot –Confirm
""
}
else
{
""
"The Snapshot $Snapshot is not older than $tdate, or $dagen day(s) ago"
""
}
}
}
}
 

Search site