C# 实现 Hyper-V 虚拟机 管理
工具类如下:
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) == )
{
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) == )
{
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) == )
{
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 "" == 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) == )
{
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(, ), "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) == )
{
o = vm.InvokeMethod("RequestStateChange", new object[] { toStateCode });
break;
}
}
return "" == o.ToString();
}
private static VMState ConvertStrToVMState(string statusCode)
{
VMState vmState = VMState.Undefined;
switch (statusCode)
{
case "":
vmState = VMState.Unknown;
break;
case "":
vmState = VMState.Enabled;
break;
case "":
vmState = VMState.Disabled;
break;
case "":
vmState = VMState.Paused;
break;
case "":
vmState = VMState.Suspended;
break;
case "":
vmState = VMState.Starting;
break;
case "":
vmState = VMState.Snapshotting;
break;
case "":
vmState = VMState.Saving;
break;
case "":
vmState = VMState.Stopping;
break;
case "":
vmState = VMState.Pausing;
break;
case "":
vmState = VMState.Resuming;
break;
}
return vmState;
}
private static string ConvertVMStateToStr(VMState vmState)
{
string status = string.Empty;
switch (vmState)
{
case VMState.Unknown:
status = "";
break;
case VMState.Enabled:
status = "";
break;
case VMState.Disabled:
status = "";
break;
case VMState.Paused:
status = "";
break;
case VMState.Suspended:
status = "";
break;
case VMState.Starting:
status = "";
break;
case VMState.Snapshotting:
status = "";
break;
case VMState.Saving:
status = "";
break;
case VMState.Stopping:
status = "";
break;
case VMState.Pausing:
status = "";
break;
case VMState.Resuming:
status = "";
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;
}
}
}
C# 实现 Hyper-V 虚拟机 管理的更多相关文章
- windows server 2008 r2 企业版 hyper v做虚拟化的相关问题处理
windows server 2008 r2 企业版 hyper v做虚拟化的相关问题处理 今天在dell r710 上用windows server 2008 r2企业版hyper v 做虚拟化,添 ...
- Hyper V NAT 网络设置 固定IP / DHCP
Hyper V 默认的Default Switch同时支持了NAT网络以及DHCP,虚拟机能够访问外网. 但使用过程中发现这个IP网段经常变化,而且Hyper V没有提供管理其NAT网络与DHCP的图 ...
- 设置Hyper V
1.打开服务器管理器 2.添加角色和功能 3.安装类型 -> 基于角色或基于功能的安装 4.服务器选择 -> 下一步 5.服务器角色 勾选"Hyper V"
- kvm虚拟机管理 系统自动化安装
原创博文安装配置KVM http://www.cnblogs.com/elvi/p/7718574.htmlweb管理kvm http://www.cnblogs.com/elvi/p/7718582 ...
- libvirt工具实现虚拟机管理
libvirt工具实现虚拟机管理 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.介绍virt-install命令的常用参数 virt-install是一个命令行工具,它能够为K ...
- [转载]【虚拟化系列】VMware vSphere 5.1 虚拟机管理
转载自:http://mabofeng.blog.51cto.com/2661587/1019497 在上一博文中我们安装了强大的VMware vCenter管理中心,通过VMware vSphere ...
- kvm虚拟机管理基础
部署 KVM 虚拟机 a.kvm 安装 环境:centos7,cpu 支持虚拟化,关闭 selinux,关闭 firewalld yum install libvirt virt-install qe ...
- HYPER -V 独立安装的 2016版本 中文版 下载好慢啊
HYPER -V 独立安装的 2016版本 中文版 下载好慢啊
- KVM -> 虚拟机管理&console登录_02
1.KVM虚拟机管理操作 virsh命令常用参数总结 1.开机关机: virsh list (只可以查看运行的虚拟机) virsh list --all (全部都可以查看) 开机与关机: virsh ...
随机推荐
- windows和ubuntu 10.4双启动顺序
改动/boot/grub/grub.cfg文件 /boot/grub/grub.cfg文件,这与旧版本号不同(9.10之前版本号/boot/grub/menu.lst),并且为了安全起见,该文件默觉得 ...
- 2014.06.14 GlusterFS技术交流视频
6月14线下GlusterFS视频交流.高清视频是非常好的,我初听言论方面,谈到迅速,似乎不是很清楚,讲座结束后速度需要改进.谢谢能力的天空AbleSky高大内设,谢谢学生参加. 在线公开课:http ...
- DotNetOpenAuth实践
DotNetOpenAuth实践之搭建验证服务器 DotNetOpenAuth是OAuth2的.net版本,利用DotNetOpenAuth我们可以轻松的搭建OAuth2验证服务器,不废话,下面我们来 ...
- Cocos2d-x 2.2.3 Android配置
今天总结出来的部署流程,已经成功把自己的项目编译到android真机上.省去了安装ndk等步骤 环境: win7 64位 1.导入项目到eclipse 2.导入libcocos2dx 样例:C:\co ...
- Ajax基础知识(二)
接上一篇 Ajax基础知识(一) 在上一篇博客里,抛弃了VS中新建aspx页面,拖个button写上C#代码的方式.使用ajax的方式,异步向服务器请求数据.我们让服务器只简单的返回一个" ...
- SharePoint 2013 配置启用搜索服务
原文:SharePoint 2013 配置启用搜索服务 1.安装完毕SharePoint 2013,新建网站集,点击搜索,出现如下错误(因为没配置,别激动). 2.尝试启动服务器场中的服务之Share ...
- hibernate 单元測试框架
hibernate在写数据库配置文件时很的不确定,必须进行必要的測试保证数据库结构的正确性.所以能够应用junit进行測试. 使用junit很easy,eclipse仅仅须要右键项目新建一个junit ...
- [jQuery1.9]Cannot read property ‘msie’ of undefined错误的解决方法
原文:[jQuery1.9]Cannot read property 'msie' of undefined错误的解决方法 $.browser在jQuery1.9里被删除了,所以项目的js代码里用到$ ...
- 产品 线上 保持 和 支持 服务 (Support and maintenance solutions)
Maintenance and support are the key factors for the smooth functioning of ERP solutions. ERP mainten ...
- shell文字过滤程序(十一):paste命令
[版权声明:转载请保留源:blog.csdn.net/gentleliu.Mail:shallnew at 163 dot com] 由于可以从字面上可以看出.paste指挥和cut相反的命令.cut ...