hyper-V 虚拟机的创建和内存管理

在Hyper-V的管理界面中可以根据向导轻易的创建出一台虚拟机,不过Hyper-V作为企业级的应用,还提供了WMI接口供外部操作.
 
以C#为例来通过程序创建VM.
需要通过 Msvm_VirtualSystemManagementService.DefineVirtualSystem方法来创建一个虚拟机
 
// Get Msvm_VirtualSystemManagementService Object
ManagementClass
mc = new ManagementClass(scope, new ManagementPath("Msvm_VirtualSystemManagementService"), null);
ManagementObject  objVSMS = null
foreach  ( ManagementObject  obj  in  mc.GetInstances())
{
   objVSMS =  obj;
}
inParams = objVSMS.GetMethodParameters(
"DefineVirtualSystem");
// Create   Msvm_VirtualSystemGlobalsettingData Object
ManagementPath
wmiPath =  new   ManagementPath ("Msvm_VirtualSystemGlobalsettingData");
ManagementClass  serviceClass =  new   ManagementClass (scope, wmiPath,  null );
ManagementObject  data= serviceClass.CreateInstance();
data[
"ElementName"] = "vmName";
data[
"ExternalDataRoot"] = "c:\vms\vmName"; // VM Path, if don't specify, it will use default
data[
"SnapshotDataRoot"] = "c:\snapshots\vmName"; // snapshot path, if don't specify, it will be same with ExternalDataRoot
inParams[
"ResourcesettingData"] = null;
inParams[
"Sourcesetting"] = null;
inParams[
"SystemsettingData"] = data.GetText(TextFormat.CimDtd20);
outParams = objVSMS.InvokeMethod(
"DefineVirtualSystem", inParams, null);
 

Remark:这样创建出来的VM不包含任何资源(内存除外), 如果要想使用,还需要给它创建硬盘,网卡的资源文件.

如何取得已经存在的VM?
select * from Msvm_ComputerSystem Where ElementName = 'vmName
'"
 
如何打开关闭VM
 Msvm_ComputerSystem.RequestStateChange // 2 - turn on VM, 3 - turn off vm
 如果装了VM里的OS装了VM guest,还可以通过Msvm_ShutdownComponent.InitiateShutdown 来安全的关闭VM
 SELECT * FROM Msvm_ShutdownComponent WHERE SystemName='vmName'   可以取得Msvm_ShutdownComponent对象
 
如何取得内存对象

  SELECT * FROM Msvm_MemorySettingData WHERE InstanceID LIKE "%Microsoft:vmName%"

如何修改内存大小
Msvm_MemorySettingData   对象的VirtualQuantity,Reservation,Limit 定义了内存的大小,用Msvm_VirtualSystemManagementService.ModifyVirtualSystemResources可以改变内存的大小

你可能感兴趣的:(内存管理)