I regularly have customers who have problems with staff creating snapshots and forgetting to clean them up. This can lead to any number of issues, especially snapshots growing out of control and filling up a datastore. To help prevent this from happening, I’ve started creating a scheduled task (with their blessing, of course) to delete snapshots older than an agreed upon amount of days. You could approach this in lots of ways, but due to my love of PowerCLI, I decided to go that route. If you have this problem in your environment, check out the below snippet to clean it up!

So that this can be run as a Scheduled Task, you’ll need to provide credentials ahead of time for the Connect-VIServer operation. Use the New-VICredentialStoreItem cmdlet to create the credentials ahead of time, and then modify the path in the script to point to them.

One last thing – for tips on how to run a PowerCLI script as a scheduled task, check out this post from @alanrenouf — Running a PowerCLI Scheduled Task

[code language=”ps”] # How many days should we keep snapshots?$howLong = 2

#—————————————–#

$creds = Get-VICredentialStoreItem -Host "[vCenter FQDN]" -File "D:Scriptscreds.xml"

Connect-VIServer [vCenter FQDN] -User $creds.user -Password $creds.password

$age = (Get-Date).AddDays(-$howLong)

Get-VM | Get-Snapshot | Foreach {

if($_.Created -lt $age){

Remove-Snapshot $_ -Confirm:$false

}

}

[/code]