// Clones a virtual machine and creates new machines based on the comma sep. string passed in.
public bool CloneVirtualSystem()
{
// Init everything we will need.
bool fRet = false;
bool fSuccess = false;
VirtualMachine oVirtualMachine = null;
ManagedObjectReference morTask = new ManagedObjectReference();
VirtualMachineCloneSpec oVirtualMachineCloneSpec = new VirtualMachineCloneSpec();
VirtualMachineRelocateSpec oVirtualMachineRelocateSpec = new VirtualMachineRelocateSpec();
Datastore oDatastore = null;
Task oTask = null;
Folder oFolder = null;
try
{
// Try and connect to the host
fSuccess = ConnectToEsxServer(m_sUsername, m_sPassword, m_sEsxServer);
// If we successfully connected, get the virtual machine object
if (fSuccess)
{
oVirtualMachine = GetVirtualMachineObject();
}
// If we have a valid virtual machine object, proceed
if (oVirtualMachine != null)
{
// Grab the datastore for the current VM (the new VM will be created in the same location
oDatastore = (Datastore)m_oVimClient.GetView(oVirtualMachine.Datastore[0], null);
// Setup the relocate and clone spec.
oVirtualMachineRelocateSpec.Host = m_oHostSystem.MoRef;
oVirtualMachineRelocateSpec.Pool = oVirtualMachine.ResourcePool;
oVirtualMachineRelocateSpec.Datastore = oDatastore.MoRef;
oVirtualMachineRelocateSpec.Transform = VirtualMachineRelocateTransformation.sparse;
oVirtualMachineCloneSpec.Template = false;
oVirtualMachineCloneSpec.PowerOn = false;
oVirtualMachineCloneSpec.Location = oVirtualMachineRelocateSpec;
// Grab the vm folder from the datacenter object
oFolder = (Folder)m_oVimClient.GetView(m_oDatacenter.VmFolder, null);
// Clone the machine
morTask = oVirtualMachine.CloneVM_Task(oFolder.MoRef, "TestClone", oVirtualMachineCloneSpec);
// Grab the task
oTask = (Task)m_oVimClient.GetView(morTask, null);
// Monitor it for completion
fRet = EvalulateVmTask(ref oTask, ref morTask);
}
}
catch (VimException exp)
{
m_oLogging.Error(m_sVirtualMachine + ": CloneVirtualSystem() failed with error " + exp.Message);
Console.Write(m_sVirtualMachine + ": CloneVirtualSystem() failed with error " + exp.Message);
return fRet;
}
catch (Exception exp)
{
m_oLogging.Error(m_sVirtualMachine + ": CloneVirtualSystem() failed with error " + exp.Message);
Console.Write(m_sVirtualMachine + ": CloneVirtualSystem() failed with error " + exp.Message);
return fRet;
}
// Return the results
return fRet;
}