PowerCLI: Reset VM to Current Snapshot

21 Jun 2018
 

One thing I often found myself doing with the VMWare vSphere client is resetting VMs to their previous snapshot, therefore ‘cleaning’ them. I’ve since started using PowerCLI for almost everything, however, I couldn’t find a simple way to use if for resetting VMs, the built-in cmdlets requiring you to name a specific snapshot (please let me know if there’s something I’ve missed!).

To get around this I wrote a simple function that will just reset any VM to its most recent snapshot, which I keep, along with some other PowerCLI related functions, in a PowerShell module that gets imported whenever I connect to the server:

function Reset-VMToCurrentSnapshot {
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true,
        ValueFromPipeline)]
        [string] $VM,

        [parameter(Mandatory = $false)]
        [switch] $confirm = $true
    )

    PROCESS {
        $doit = $true
        $snap = Get-Snapshot -VM $VM | where {$_.IsCurrent -eq $true}
        if (((Get-VM $VM).PowerState -eq "PoweredOn") -and $confirm) {
            $title = "Revert $VM to $snap"
            $message = "$VM is powered on, are you sure you want to revert it?"
            $yes = New-Object `
                System.Management.Automation.Host.ChoiceDescription "&Yes", `
                "Revert $VM to $snap."
            $no = New-Object `
                System.Management.Automation.Host.ChoiceDescription "&No", `
                "Don't revert $VM."
            $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
            $result = $host.ui.PromptForChoice($title, $message, $options, 0)
            switch ($result)
                {
                    0 {
                        Write-Verbose "Reverting $VM."
                    }
                    1 {
                        Write-Host "Leaving $VM as is."
                        $doit = $false
                    }
                }
        }

        if ($doit) {
            Write-Verbose "Setting $VM to $snap..."
            Set-VM -VM $VM -SnapShot $snap -Confirm:$false
            Write-Verbose "Done!"
        }
    }
}