Remove Snapshots script

One approach to selectively delete snapshots in a vCenter, specifically targeting those created by specific individuals, involves utilizing a ‘TAG’ system applied to either the snapshot name or description. This method allows for the identification and subsequent deletion of snapshots based on the specified criteria, rather than removing all snapshots across the vCenter environment.

Usage:

.\remove-snapshots.ps1 -vcenter vcsa.local -username * -password * -tag “autodelete”

Script

#requires -modules VMware.VimAutomation.Core

param (
    [CmdletBinding()]
    [Parameter(Mandatory = $true)]
    [string]$VCenter,
     
    [Parameter(Mandatory = $true)]
    [string]$Username,
     
    [Parameter(Mandatory = $true)]
    [string]$Password,

    [Parameter(Mandatory = $true)]
    [string]$tag
)
 
Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue
Set-PowerCLIConfiguration -ProxyPolicy NoProxy -DefaultVIServerMode multiple -Scope User -InvalidCertificateAction ignore -Confirm:$false | Out-Null
 
# Connection to vCenter
try {
    Connect-VIServer -Server $VCenter -User $Username -Password $Password -ErrorAction Stop | Out-Null
}
catch [VMware.VimAutomation.ViCore.Types.V1.ErrorHandling.InvalidLogin] {
    Write-Host "Cannot connect to $VCenter with provided credentials" -ForegroundColor Red
    Continue
}
catch [VMware.VimAutomation.Sdk.Types.V1.ErrorHandling.VimException.ViServerConnectionException] {
    Write-Host "Cannot connect to $VCenter - check IP/FQDN" -ForegroundColor Red
    Continue
}
catch {
    Write-Host "Cannot connect to $VCenter - Unknown error" -ForegroundColor Red
    Continue
}

$limit= (Get-Date).AddDays(-10)

Get-VM | Sort | Get-Snapshot | Where-Object {($_.Created -lt $limit) -and ($_.Name -like "*$($tag)*")} | Remove-Snapshot -RunAsync -Confirm:$false
Get-VM | Sort | Get-Snapshot | Where-Object {($_.Created -lt $limit) -and ($_.Description -like "*$($tag)*")} | Remove-Snapshot -RunAsync -Confirm:$false

Disconnect-VIserver -Server $vcu -Confirm:$false
 

Loading