Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Name

Description

Last Modified Date

Download

RevertSnapShot.ps1

Reverts to the last snapshot using VMWare ESX PowerShell API

01/01/2012

RevertSnapShot.ps1 1kb
Info

This script only works with ESX.  It does not work with ESXi. 

Code Block
languagepowershell
titleRevertSnapShot.ps1
param (
    $ServerName = $(throw 'Please specify Virtual Infrastructure ServerName or IP'),
    $User = $(throw 'Please specify username'),
    $Password = $(throw 'Please specify password'),
    $VMName = $(throw 'Please specify VMName'),
    $SnapshotName = $null
)
$s = get-pssnapin | where-object {$_.Name -eq "VMWare.VimAutomation.Core" }
if($s -eq $null)
{
    add-pssnapin VMWare.VimAutomation.Core
}
function ResetSnapshot
{
    if($server -eq $null -or $server.IsConnected -eq $false)
    {
        throw 'Unable to connect to $ServerName'
    }
    $vm = Get-VM -Name $VMName
    if($vm -eq $null)
    {
        throw 'Unable to find specified VM $VMName'
    }    
    $snapShot = $null
    $snapShots = Get-SnapShot -VM $vm
    if($SnapshotName -eq $null)
    {
        if($snapShots -eq $null -or $snapShots.Count -eq 0)
        {
            throw 'No snapshots for specified VM $VMName'
        }
        $snapShot = $snapShots[$snapshots.Count - 1]    
    }
    else
    {
        $snapShot = $snapShots | Where-Object { $_.Name -ieq $SnapshotName }
    }
    if($snapShot -eq $null)
    {
        throw 'No snapshots for specified VM $VMName'
    }
    Write-Host ('Setting snapshot ' + $snapShot.Name + ' on VM ' + $vm.Name)
    Set-VM -VM $vm -Snapshot $snapShot -confirm:$false -ErrorAction:Stop
    $Message = "Restored default machine on " 
    Set-VM -VM $vm -Description $Message $vm.Name -confirm:$false -ErrorAction:Continue  
}
try
{
    cls
    $server = Connect-VIServer -Server $ServerName -User $User -Password $Password
    ResetSnapshot
}
catch
{
    Write-Error $_
    exit 1
}
finally
{
    if($server -ne $null -and $server.IsConnected -eq $true)
    {
        Disconnect-VIServer -Server $server -Confirm:$false
    }
}