private void btnCloneVm_Click(object sender, EventArgs e)
{
if (client == null)
{
MessageBox.Show("请先连接到vCenter Server", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (cboTemplates.SelectedIndex < 0)
{
MessageBox.Show("请选择虚拟模板", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (cboHostsClone.SelectedIndex < 0)
{
MessageBox.Show("请选择目标主机", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (cboDatastores.SelectedIndex < 0)
{
MessageBox.Show("请选择数据存储", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
string vmName = txtVmName.Text;
if (string.IsNullOrWhiteSpace(vmName))
{
MessageBox.Show("请输入虚拟机名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
try
{
Cursor = Cursors.WaitCursor;
VirtualMachine template = (VirtualMachine)templates[cboTemplates.SelectedIndex];
HostSystem targetHost = (HostSystem)esxiHosts[cboHosts.SelectedIndex];
Datastore targetDatastore = datastores[cboDatastores.SelectedIndex];
// 创建克隆规范
VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
cloneSpec.Location = new VirtualMachineRelocateSpec();
cloneSpec.Location.Datastore = targetDatastore.MoRef;
cloneSpec.Location.Host = targetHost.MoRef;
cloneSpec.Location.Pool = ((ComputeResource)client.GetView(targetHost.Parent, null)).ResourcePool;
cloneSpec.PowerOn = false;
cloneSpec.Template = false;
// 查找虚拟机文件夹
// 获取数据中心和文件夹
Datacenter dc = (Datacenter)client.GetView(template.Parent, null);
Folder vmFolder = (Folder)client.GetView(dc.VmFolder, null);
ManagedObjectReference[] childEntity = vmFolder.ChildEntity;
foreach (ManagedObjectReference mor in childEntity)
{
if (mor.Type == "Folder")
{
vmFolder = (Folder)client.GetView(mor, null);
break;
}
}
// 执行克隆
ManagedObjectReference reference = template.CloneVM_Task(vmFolder.MoRef, vmName, cloneSpec);
client.WaitForTask(reference);
// 获取任务状态
VMware.Vim.Task taskInfo = (VMware.Vim.Task)client.GetView(reference, null);
if (taskInfo.Info.State == TaskInfoState.success)
{
UpdateStatus($"成功从模板 '{template.Name}' 克隆虚拟机 '{vmName}' 到主机 '{targetHost.Name}'");
MessageBox.Show($"成功从模板 '{template.Name}' 克隆虚拟机 '{vmName}' 到主机 '{targetHost.Name}'", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
// 重新加载虚拟模板
LoadTemplates();
}
else
{
UpdateStatus($"克隆虚拟机失败: {taskInfo.Info.Error.LocalizedMessage}");
MessageBox.Show($"克隆虚拟机失败: {taskInfo.Info.Error.LocalizedMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
UpdateStatus($"克隆虚拟机时出错: {ex.Message}");
MessageBox.Show($"克隆虚拟机时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Cursor = Cursors.Default;
}
}Folder vmFolder = (Folder)client.GetView(dc.VmFolder, null);{"无法将类型为“VMware.Vim.Folder”的对象强制转换为类型“VMware.Vim.Datacenter”。"}