VMW_RemoveOldSnapshots.ps1


<#PSScriptInfo
 
.VERSION 1.1
 
.GUID 897cb0d5-76d2-41e7-96ef-f2ca7eb5a143
 
.AUTHOR Andrew Anderson - Twitter @drewjanderson
 
.COMPANYNAME AndersonTech
 
.COPYRIGHT
 
.TAGS PowerCLI VMware Snapshots
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES PowerCLI
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
Added Param block to enable running this script and passing in the day value as well as vCenter Server name.
 
#>
 



<#
 
.DESCRIPTION
 This script removes VMware VM snapshots that are older than 14 days
 
#>
 

[CmdletBinding()]
Param(
    [Parameter(Mandatory=$true,HelpMessage='Enter number of days for the oldest snapshot to be kept.')]
    [string]$DeleteOlderThan,

    [Parameter(Mandatory=$true,HelpMessage='Enter your vCenter server name')]
    [string]$VIServer
)

# Imports PowerCLI Module
Import-Module VMware.VimAutomation.Core

# Connects to the vCenter or ESXi servers
Connect-VIServer $VIServer

# Collects VM snapshot information for all VMs where the snapshots are older than days specified
$snapshots = Get-VM | Get-Snapshot | Where-Object {$_.Created -lt (Get-Date).AddDays(-$DeleteOlderThan)}

# Removes snapshots older than days specified
$snapshots | Remove-Snapshot -RemoveChildren -RunAsync -Confirm:$false

# Disconnects from the connected vCenter or ESXi servers
Disconnect-VIServer $VIServer -Confirm:$false

# Unloads the PowerCLI module
Remove-Module VMware.VimAutomation.Core