在vmware的PowerCLI和微软的scvmm的PowerShell中可以通过Get-VM命令来获取虚拟机的信息。下面我们用代码的方式去实现,代码相关类方法就是对命令的封装。
vmware api的调用方式:
#region vm status public VirtualMachineOperationEnum GetVMStatus(string vmName) { ManagedObjectReference vmMor = util.getServiceUtil().getEntityByName("VirtualMachine", vmName); VirtualMachineRuntimeInfo info = (VirtualMachineRuntimeInfo)util.getServiceUtil().GetDynamicProperty(vmMor, "runtime"); switch (info.powerState) { case VirtualMachinePowerState.poweredOn: return VirtualMachineOperationEnum.On; case VirtualMachinePowerState.poweredOff: return VirtualMachineOperationEnum.Off; case VirtualMachinePowerState.suspended: return VirtualMachineOperationEnum.Suspend; default: return VirtualMachineOperationEnum.Fault; } } #endregion
微软api的调用方式:
1 #region vm status 2 public VirtualMachineOperationEnum GetVMStatus(string vmName) 3 { 4 try 5 { 6 switch (client.GetVirtualMachineByName(vmName).Status) 7 { 8 case DataContracts.VMComputerSystemStateInfo.Running: 9 return VirtualMachineOperationEnum.On; 10 case DataContracts.VMComputerSystemStateInfo.Paused: 11 return VirtualMachineOperationEnum.Paused; 12 case DataContracts.VMComputerSystemStateInfo.PowerOff: 13 return VirtualMachineOperationEnum.Off; 14 default: 15 return VirtualMachineOperationEnum.Fault; 16 } 17 } 18 catch { return VirtualMachineOperationEnum.Fault; } 19 } 20 #endregion