C# 实现 Hyper-V 虚拟机 管理

Hyper-V WMI Provider

工具类如下:

using System;
using System.Collections.Generic;
using System.Management;

namespace MyNamespace
{
#region Return Value of RequestStateChange Method of the Msvm_ComputerSystem Class
//Return Value of RequestStateChange Method of the Msvm_ComputerSystem Class
//This method returns one of the following values.
//Completed with No Error (0)
//DMTF Reserved (7–4095)
//Method Parameters Checked - Transition Started (4096)
//Failed (32768)
//Access Denied (32769)
//Not Supported (32770)
//Status is unknown (32771)
//Timeout (32772)
//Invalid parameter (32773)
//System is in use (32774)
//Invalid state for this operation (32775)
//Incorrect data type (32776)
//System is not available (32777)
//Out of memory (32778)
#endregion

public class VMManagement
{
private static string hostServer = "hostServer";
private static string userName = "username";
private static string password = "password";

public static string HostServer
{
get;
set;
}

public static string UserName
{
get;
set;
}

public static string Password
{
get;
set;
}

public static VMState GetVMState(string vmName)
{
VMState vmState
= VMState.Undefined;
ConnectionOptions co
= new ConnectionOptions();
co.Username
= userName;
co.Password
= password;

ManagementScope manScope
= new ManagementScope(string.Format(@"\\{0}\root\virtualization", hostServer), co);
manScope.Connect();

ObjectQuery queryObj
= new ObjectQuery("SELECT * FROM Msvm_ComputerSystem");
ManagementObjectSearcher vmSearcher
= new ManagementObjectSearcher(manScope, queryObj);
ManagementObjectCollection vmCollection
= vmSearcher.Get();

foreach (ManagementObject vm in vmCollection)
{
if (string.Compare(vm["ElementName"].ToString(), vmName, true) == 0)
{
vmState
= ConvertStrToVMState(vm["EnabledState"].ToString());
break;
}
}

return vmState;
}

public static bool StartUp(string vmName)
{

return ChangeVMState(vmName, VMState.Enabled);
}

public static bool ShutDown(string vmName)
{
return ChangeVMState(vmName, VMState.Disabled);
}

public static bool RollBack(string vmName, string snapShotName)
{
ConnectionOptions co
= new ConnectionOptions();
co.Username
= userName;
co.Password
= password;

ManagementScope manScope
= new ManagementScope(string.Format(@"\\{0}\root\virtualization", hostServer), co);
manScope.Connect();

ObjectQuery queryObj
= new ObjectQuery("SELECT * FROM Msvm_ComputerSystem");
ManagementObjectSearcher vmSearcher
= new ManagementObjectSearcher(manScope, queryObj);
ManagementObjectCollection vmCollection
= vmSearcher.Get();

object opResult = null;
// loop the virtual machines
foreach (ManagementObject vm in vmCollection)
{
// find the vmName virtual machine, then get the list of snapshot
if (string.Compare(vm["ElementName"].ToString(), vmName, true) == 0)
{
ObjectQuery queryObj1
= new ObjectQuery(string.Format("SELECT * FROM Msvm_VirtualSystemSettingData WHERE SystemName='{0}' and SettingType=5", vm["Name"].ToString()));
ManagementObjectSearcher vmSearcher1
= new ManagementObjectSearcher(manScope, queryObj1);
ManagementObjectCollection vmCollection1
= vmSearcher1.Get();
ManagementObject snapshot
= null;
// find and record the snapShot object
foreach (ManagementObject snap in vmCollection1)
{
if (string.Compare(snap["ElementName"].ToString(), snapShotName, true) == 0)
{
snapshot
= snap;
break;
}
}

ObjectQuery queryObj2
= new ObjectQuery("SELECT * FROM Msvm_VirtualSystemManagementService");
ManagementObjectSearcher vmSearcher2
= new ManagementObjectSearcher(manScope, queryObj2);
ManagementObjectCollection vmCollection2
= vmSearcher2.Get();

ManagementObject virtualSystemService
= null;
foreach (ManagementObject o in vmCollection2)
{
virtualSystemService
= o;
break;
}

if (ConvertStrToVMState(vm["EnabledState"].ToString()) != VMState.Disabled)
{
ShutDown(vm[
"ElementName"].ToString());
}
opResult
= virtualSystemService.InvokeMethod("ApplyVirtualSystemSnapShot", new object[] { vm.Path, snapshot.Path });
break;
}
}

return "0" == opResult.ToString();
}

public static List<SnapShot> GetVMSnapShotList(string vmName)
{
List
<SnapShot> shotList = new List<SnapShot>();
ConnectionOptions co
= new ConnectionOptions();
co.Username
= userName;
co.Password
= password;

ManagementScope manScope
= new ManagementScope(string.Format(@"\\{0}\root\virtualization", hostServer), co);
manScope.Connect();

ObjectQuery queryObj
= new ObjectQuery("SELECT * FROM Msvm_ComputerSystem");
ManagementObjectSearcher vmSearcher
= new ManagementObjectSearcher(manScope, queryObj);
ManagementObjectCollection vmCollection
= vmSearcher.Get();

string str = "";
// loop through the machines
foreach (ManagementObject vm in vmCollection)
{

str
+= "Snapshot of " + vm["ElementName"].ToString() + "\r\n";
//Get the snaplist
if (string.Compare(vm["ElementName"].ToString(), vmName, true) == 0)
{
ObjectQuery queryObj1
= new ObjectQuery(string.Format("SELECT * FROM Msvm_VirtualSystemSettingData WHERE SystemName='{0}' and SettingType=5", vm["Name"].ToString()));
ManagementObjectSearcher vmSearcher1
= new ManagementObjectSearcher(manScope, queryObj1);
ManagementObjectCollection vmCollection1
= vmSearcher1.Get();

foreach (ManagementObject snap in vmCollection1)
{
SnapShot ss
= new SnapShot();
ss.Name
= snap["ElementName"].ToString();
ss.CreationTime
= DateTime.ParseExact(snap["CreationTime"].ToString().Substring(0, 14), "yyyyMMddHHmmss", null).ToLocalTime();
ss.Notes
= snap["Notes"].ToString();
shotList.Add(ss);
}
}
}

return shotList;
}

private static bool ChangeVMState(string vmName, VMState toState)
{
string toStateCode = ConvertVMStateToStr(toState);
if (toStateCode == string.Empty)
return false;

ConnectionOptions co
= new ConnectionOptions();
co.Username
= userName;
co.Password
= password;

ManagementScope manScope
= new ManagementScope(string.Format(@"\\{0}\root\virtualization", hostServer), co);
manScope.Connect();

ObjectQuery queryObj
= new ObjectQuery("SELECT * FROM Msvm_ComputerSystem");
ManagementObjectSearcher vmSearcher
= new ManagementObjectSearcher(manScope, queryObj);
ManagementObjectCollection vmCollection
= vmSearcher.Get();

object o = null;
foreach (ManagementObject vm in vmCollection)
{
if (string.Compare(vm["ElementName"].ToString(), vmName, true) == 0)
{
o
= vm.InvokeMethod("RequestStateChange", new object[] { toStateCode });
break;
}
}
return "0" == o.ToString();
}

private static VMState ConvertStrToVMState(string statusCode)
{
VMState vmState
= VMState.Undefined;

switch (statusCode)
{
case "0":
vmState
= VMState.Unknown;
break;
case "2":
vmState
= VMState.Enabled;
break;
case "3":
vmState
= VMState.Disabled;
break;
case "32768":
vmState
= VMState.Paused;
break;
case "32769":
vmState
= VMState.Suspended;
break;
case "32770":
vmState
= VMState.Starting;
break;
case "32771":
vmState
= VMState.Snapshotting;
break;
case "32773":
vmState
= VMState.Saving;
break;
case "32774":
vmState
= VMState.Stopping;
break;
case "32776":
vmState
= VMState.Pausing;
break;
case "32777":
vmState
= VMState.Resuming;
break;
}

return vmState;
}

private static string ConvertVMStateToStr(VMState vmState)
{
string status = string.Empty;
switch (vmState)
{
case VMState.Unknown:
status
= "0";
break;
case VMState.Enabled:
status
= "2";
break;
case VMState.Disabled:
status
= "3";
break;
case VMState.Paused:
status
= "32768";
break;
case VMState.Suspended:
status
= "32769";
break;
case VMState.Starting:
status
= "32770";
break;
case VMState.Snapshotting:
status
= "32771";
break;
case VMState.Saving:
status
= "32773";
break;
case VMState.Stopping:
status
= "32774";
break;
case VMState.Pausing:
status
= "32776";
break;
case VMState.Resuming:
status
= "32777";
break;
}

return status;
}
}

/// <summary>
///- Undefined --> "Not defined"
///0 Unknown --> "Unknown"
///2 Enabled --> "Running"
///3 Diabled --> "Off"
///32768 Paused --> "Paused"
///32769 Suspended --> "Saved"
///32770 Starting --> "Starting"
///32771 Snapshotting --> "Snapshooting
///32773 Saving --> "Saving"
///32774 Stopping --> "Shuting down
///32776 Pausing --> "Pausing"
///32777 Resuming --> "Resuming"
/// </summary>
public enum VMState
{
Undefined,
Unknown,
Enabled,
Disabled,
Paused,
Suspended,
Starting,
Snapshotting,
Saving,
Stopping,
Pausing,
Resuming
}

public class SnapShot
{
public string Name
{
get;
set;
}

public DateTime CreationTime
{
get;
set;
}

public string Notes
{
get;
set;
}
}
}

 

转载于:https://www.cnblogs.com/Peter-Zhang/archive/2011/09/17/2179634.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
刚学C#时就一直想找到一种方法可以让.Net程序在未安装framework的电脑上运行,但一直没有找到真正可用的。虽然有些公司发布了可以将.net代码编译成navtive代码以脱离.net环境运行,如Remotesoft DOTNET Linker,Xenocode Postbuild等,但一直没有破解版,用它们编译的程序每次运行会添出个版权信息。最近偶然发现一种方法可以做到真正使程序脱离.net环境运行且没有任何版权信息添出,现将使用方法、源代码、测试程序发布于此: 请首先在文章末尾下载测试程序,是一个用C#做的串口工具,下载解压后有两个文件夹(FrameWork和APP)和一个程序(串口工具.exe),在APP文件夹下有一个名为9527.exe的程序,这个是C#真正的“串口工具.exe”,而主目录下的串口工具.exe只是一个Loader程序,它运行后首先判断电脑上有没有安装framework,若有,则直接启动APP下的9527.exe程序;若无,则通过framework虚拟机(FrameWork下的VM.exe(其实是飞信框架里的FetionVM.exe,修改了它的图标和版权,想改成其它的大家可以用VC改一下,有网友强列要求指出这一点,想不明白为什么,呵呵,让指出就指出吧,还要求指出调用的方法,,其实我连源程序都公布了,用说的这么明白吗))启动9527.exe程序。Loader程序不会打开任何窗口,并在启动真正应用程序后立即退出。Loader程序主函数(VC6.0编写)的代码附件上有
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值