原文: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) == )
{
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 虚拟机 管理的更多相关文章

  1. windows server 2008 r2 企业版 hyper v做虚拟化的相关问题处理

    windows server 2008 r2 企业版 hyper v做虚拟化的相关问题处理 今天在dell r710 上用windows server 2008 r2企业版hyper v 做虚拟化,添 ...

  2. Hyper V NAT 网络设置 固定IP / DHCP

    Hyper V 默认的Default Switch同时支持了NAT网络以及DHCP,虚拟机能够访问外网. 但使用过程中发现这个IP网段经常变化,而且Hyper V没有提供管理其NAT网络与DHCP的图 ...

  3. 设置Hyper V

    1.打开服务器管理器 2.添加角色和功能 3.安装类型 -> 基于角色或基于功能的安装 4.服务器选择 -> 下一步 5.服务器角色 勾选"Hyper V"

  4. kvm虚拟机管理 系统自动化安装

    原创博文安装配置KVM http://www.cnblogs.com/elvi/p/7718574.htmlweb管理kvm http://www.cnblogs.com/elvi/p/7718582 ...

  5. libvirt工具实现虚拟机管理

    libvirt工具实现虚拟机管理 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.介绍virt-install命令的常用参数 virt-install是一个命令行工具,它能够为K ...

  6. [转载]【虚拟化系列】VMware vSphere 5.1 虚拟机管理

    转载自:http://mabofeng.blog.51cto.com/2661587/1019497 在上一博文中我们安装了强大的VMware vCenter管理中心,通过VMware vSphere ...

  7. kvm虚拟机管理基础

    部署 KVM 虚拟机 a.kvm 安装 环境:centos7,cpu 支持虚拟化,关闭 selinux,关闭 firewalld yum install libvirt virt-install qe ...

  8. HYPER -V 独立安装的 2016版本 中文版 下载好慢啊

    HYPER -V 独立安装的 2016版本 中文版 下载好慢啊

  9. KVM -> 虚拟机管理&console登录_02

    1.KVM虚拟机管理操作 virsh命令常用参数总结 1.开机关机: virsh list (只可以查看运行的虚拟机) virsh list  --all (全部都可以查看) 开机与关机: virsh ...

随机推荐

  1. Linux 多学习过程

    1Linux流程概述 过程是,一旦运行过程中的程序,他和程序本质上的区别.程序是静态的,他奉命收集指令存储在磁盘上. 进程是动态的概念.他是执行者的程序,包括进程的动态创建.调度和消亡,是Linux的 ...

  2. Iterator、Iterable接口的使用及详解

    Java集合类库将集合的接口与实现分离.同样的接口,可以有不同的实现. Java集合类的基本接口是Collection接口.而Collection接口必须实现Iterator接口. 以下图表示集合框架 ...

  3. 建立ORACLE10G DATA GUARD---&gt;Physical Standby

    下面是我自己建Physical Standby,按照下面的步骤一步我一步,当然,打造成功,以下步骤可以作为建筑物Data Guard结构操作手册. HA和DG差额:HA:可以做IP切换自己主动  DG ...

  4. Maven+Spring

    Maven+Spring 关于Maven Maven是一个用于项目构建的工具,通过它便捷的管理项目的生命周期.即项目的jar包依赖,开发,测试,发布打包. 做过.NET的人应该会联想到Nuget,是的 ...

  5. nodejs 复制、移动文件

    对路径没有做验证 复制文件 var fs = require('fs'); var path = require('path'); var fileName = "coverflow-3.0 ...

  6. 视频和音频播放的演示最简单的例子6:OpenGL广播YUV420P(T经exture,采用Shader)

    ===================================================== 最简单的视频和音频播放的演示样品系列列表: 最简单的视音频播放演示样例1:总述 最简单的视音 ...

  7. Ping azure

    最近azure在虚拟机上打开(欧式世纪互联),这其实并不能ping虚拟机! 查了一下资料,发现azure不支持被ping这个功能(貌似是不开放ICMP-in这个协议).有些用户跟客服问过这个问题,可是 ...

  8. Team Foundation Server 2015使用教程--团队项目创建

  9. ORDER BY RAND()

    大概是因为需要研究了一下MYSQL随机样本实现.例如:离tablename表随机抽取了创纪录,我们一般的写法是:SELECT * FROM tablename ORDER BY RAND() LIMI ...

  10. “jquery于each方法和选择”学习笔记

    <head> <title></title> <script src="jquery-1.4.2.js" type="text/ ...