Nigel Boulton's Blog

Taking Snaphots of all Virtual Machines using PowerCLI

I recently needed to apply a limited distribution patch to a number of Citrix servers, all of which are virtual on VMware ESXi 4.0. I wanted to take snapshots before doing this, to give me an easy backout route if things went horribly wrong. Of course I could always have done this using the VI Client, but that would have meant an awful lot of "mousing about" and clicking to be able to do this for 176 virtual machines.

With PowerCLI this is a cinch, in fact it's pretty much a one-liner! I chose to do this one host at a time, but with a small change to the code below you can easily expand this to encompass a larger chunk, or even all, of your virtual infrastructure.

First, connect to your vCenter Server (and provide the appropriate credentials when prompted):

Connect-VIServer -Server

Then run the following one-liner to take a snapshot of all VMs on a given host:

Get-VMHost | Get-VM | New-Snapshot -Name "Pre patch" -Quiesce

In this case I chose to quiesce the file system first. Other options are available - see the help for the New-Snapshot cmdlet.

Once you have finished with the snapshots, delete them as follows:

Get-VMHost | Get-VM | Get-Snapshot -Name "Pre patch" | Remove-Snapshot

And finally, disconnect from your vCenter Server:

Disconnect-VIServer -Server

How easy is that..?!

My good friends Alan Renouf and Jonathan Medd talk about how useful PowerCLI is for automating repetitive tasks in Episode 20 of the Get-Scripting Podcast, and this is a perfect example of that.

On the subject of the Get-Scripting Podcast, do be sure to check out Episode 20 - the guys interview none other than Jeffrey Snover, Lead Architect for Windows Server at Microsoft, and the man behind Windows PowerShell itself - excellent!

Comments (2) Trackbacks (0)
  1. thanks, Nigel, works a treat – for the removing a snapshot added the confirmation parameter, so it doesn’t prompt you on each snapshot : -Confirm:$false

    • Thanks Vic. The Confirm parameter is very useful, but it goes without saying that you need to be 100% sure of what you are doing before you set it to $False!

      A number of cmdlets (PowerShell and PowerCLI) support this parameter. Use the following to find out which:

      Get-Help * -Parameter Confirm

Leave a comment

No trackbacks yet.