VMware PowerCLI Scripts: Delete all snapshots, Create new snapshots

I've started the process of automatically installing my Windows Server updates. Since it is going to be automatic I wanted a way to delete and create new snapshots before patch Tuesdays so I could recover easily if something goes wrong.

These scripts assume your working as an AD user that has proper access to the vcenter server.

Delete all snapshots:

Code:

add-pssnapin VMware.VimAutomation.Core
Connect-VIServer -Server vcenterserver
 
        foreach ($vm in get-vm | sort-object){
            $snaps = get-snapshot -vm $vm
            $vmname = $vm.name
                foreach ($snap in $snaps){
                $snapName = $snap.name
                    if ($snapname -ne $null){
                        #"  "
                        $strOut = "Found snapshot: $snapname on: $vmname"
                        $strOut | Out-Default
                        $snap | select-object *
                        
                        # Rem the following line to perform just inventory, leave to get the remove prompt.
            remove-snapshot -snapshot $snap -confirm:$false
                    }
                    #else {"No snapshots found on $vmname"}
                    #"  "
                }
        }

Create new snapshots:

Code:

add-pssnapin VMware.VimAutomation.Core
 
Connect-VIServer -Server kohvc1-2k8r2
get-vm * | new-snapshot -name "Before Windows Updates"

I had some trouble coming up with a way to delete only a specific snapshot. As you see in the create script I am naming the snapshots "Before Windows Updates". It would be great if I could make a snapshot deletion script that only deleted those snapshots. The remove-snapshot command doesn't seem to have as many options as the create-snapshot command.

Update:

I decided to put all the servers I want to process into a folder in VMs and Templates, then query that folder with get-folder and get-vm. Here are the modified lines.

foreach ($vm in get-folder "Automatic Windows Updates" | get-vm | sort-object) {

and

get-folder "Automatic Windows Updates" | get-vm | new-snapshot -name "Before Windows Updates"

  • danielwang
    Comment from: danielwang
    10/19/11 @ 06:02:25 am

    hi
    thanks for your share.
    Use the following script " new-snapshot -name(Get-VM -name 'Win Xp') "Before Windows Updates"" . i can create a snapshot for "Win xp". But how can i set the snapshot store location?

    Wait for your reply. Thanks

  • jadams159
    Comment from: jadams159
    11/11/11 @ 06:05:00 pm

    The snapshot removal is so much easier to do this way:
    $RemSnap = Get-snapshot -vm * -Name "Before Updates"
    Remove-Snapshot -snapshot $RemSnap -Confirm:$false