How to revert Virtual Machine Snapshot by Virtual Appliance name and Snapshot Name on VMVare vSphere using vSphere Power CLI API

Was looking for code like this for some time and could not find anything useful and in one place on the internet. At the end I came up with something like this:

using System;
using System.Collections.Generic;
using VMware.Vim;
using System.Collections.Specialized;

namespace vSphereCommand
{
internal class Program
{
private static void Main(string[] args)
{
var c = new VimClient();
var sc = c.Connect("https:///sdk");
var us = c.Login("", "");

NameValueCollection filter = new NameValueCollection();
filter.Add("name", "");
IList vApps = c.FindEntityViews(typeof (VirtualApp), null, filter, null);

foreach (var tmp in vApps)
{
var vApp = tmp as VirtualApp;
if (vApp != null)
{
Console.WriteLine(vApp.Name);
IList vms = vApp.Vm;
foreach (var vm in vms)
{
var vmView = (VirtualMachine) c.GetView(vm, null);
RevertToSnapshot("", vmView, c);
}
}
vApp.PowerOnVApp();
}
}

public static void RevertToSnapshot(string sSnapshotName, VirtualMachine vm, VimClient c)
{
ManagedObjectReference snapshot = FindSnapshot(vm.Snapshot.RootSnapshotList, sSnapshotName);
VirtualMachineSnapshot vms = new VirtualMachineSnapshot(c, snapshot);
var host = (HostSystem) c.GetView(vm.Runtime.Host, null);
vms.RevertToSnapshot(host.MoRef, false);
}

private static ManagedObjectReference FindSnapshot(VirtualMachineSnapshotTree[] root, string sSnapshotName)
{
foreach (VirtualMachineSnapshotTree tree in root)
{
if (tree.Name.Equals(sSnapshotName, StringComparison.OrdinalIgnoreCase))
return tree.Snapshot;
}

foreach (VirtualMachineSnapshotTree tree in root)
{
ManagedObjectReference snap = FindSnapshot(tree.ChildSnapshotList, sSnapshotName);

if (snap != null)
return snap;
}

return null;
}
}
}

Leave a Reply