VMW_RemoveOldSnapshots.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

<#PSScriptInfo
 
.VERSION 1.2
 
.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 -Server entry for the VM info collection step that is needed if the PowerCLI configuration is set to Single.
 
#>
 





<#
 
.DESCRIPTION
 This script removes VMware VM snapshots that are older than the provided value.
 
#>
 

[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 -Server $VIServer | 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