C# 实现 Hyper-V 虚拟机 管理
原文: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;        }    }}

posted on 2014-07-08 22:40 NET未来之路 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/3832618.html

C# 实现 Hyper-V 虚拟机 管理相关推荐

  1. hyper v虚拟机启动黑屏怎么办?

    最近有用户打开VMware虚拟机却出现了开机一直黑屏的情况,挂起时能够看到显示,但是开机就黑屏.不知道该如何解决,小编为你带来hyper v虚拟机启动黑屏的解决方法,希望对你有帮助. 具体解决方法: ...

  2. w7虚拟机服务器管理器,Hyper - V (五) 在Win7中安装Hyper - V 管理工具远程操作虚拟机...

    在Win7中安装Hyper - V 管理工具远程操作虚拟机 由于在Hyper - V 中安装的虚拟机运行时鼠标会出现延迟现象,所以我们可以在客户机Win 7 上安装虚拟机. 首先从microsoft ...

  3. 微软自带虚拟机Hyper—V启用

    微软自带虚拟机 windows+r 快速启动运行页面,输入 control 或右键左下角windows标志–点击运行 跳转控制面板页面点击[程序] 点击[启用或关闭windows功能] 找到Hyper ...

  4. hpgen8服务器修改电源模式,用HP GEN8+WIN2012+Hyper V+黑群晖5.2组建家庭NAS中心 篇二:HP GEN8硬件改造...

    用HP GEN8+WIN2012+Hyper V+黑群晖5.2组建家庭NAS中心 篇二:HP GEN8硬件改造 2017-11-19 15:55:35 127点赞 945收藏 205评论 追加修改(2 ...

  5. KVM精简教程(七):常用虚拟机管理

    7.1 常用命令 virsh start x 启动名字为x的非活动虚拟机 virsh create x.xml 创建虚拟机(创建后,虚拟机立即执行,成为活动主机) virsh suspend x 暂停 ...

  6. WIN10安装Hyper V

    WIN10安装Hyper V 正常情况: Hyper-V是微软提出的一种系统管理程序虚拟化技术,能够实现桌面虚拟化. 正常情况下直接在控制面版->程序->程序和功能->启用和关闭Wi ...

  7. 虚拟机管理你的服务器,全面解析VMware的虚拟机管理解决方案

    本教程将为你讲述VMware的虚拟机管理解决方案,说起虚拟机,VMware绝对可以算的上是个中翘楚了,并且VMware的虚拟桌面结构解决方案可以起到增强管理效率,降低成本等等效用,话不多说,这就为大家 ...

  8. 运维开发必会技能之一——虚拟机管理

    Linux中的虚拟机管理 1.安装Linux下的虚拟化KVM 在安装之前我们首先的准备好镜像,这里用的是光驱文件[rhel-server-7.3-x86_64-dvd.iso] 1)安装方式一:利用镜 ...

  9. OpenNebula学习第三节之虚拟机管理

    OpenNebula学习第三节之虚拟机管理 一.背景 已经安装好OpenNebula-Front-end 已经安装好OpenNebula Node 已经把Node注册到Front-end 二.目标 看 ...

  10. 基于SCVMM对虚拟化服务器与虚拟机管理权限分配用户角色

    基于SCVMM对虚拟化服务器与虚拟机管理权限 分配用户角色 随着云计算时代的来临,越来越多的企业已经将IT环境迁移到虚拟化环境中,那么企业如何来统一管理如此多的虚拟化主机与虚拟机,通过管理平台是否能实 ...

最新文章

  1. C#Swagger使用
  2. 线段树求区间最大值RMQ(单点更新)
  3. javascript --- 编程风格
  4. 制作巴士电台彩蛋一枚
  5. 谷歌guava_Google Guava v07范例
  6. 【ECCV2020】接收论文列表part1
  7. cas服务器源码,Cas服务端源码解析
  8. 【笔记】win10上使用Magic Trackpad2触摸板
  9. 2.2 matlab矩阵变换(对角阵、三角阵、矩阵的转置、矩阵的旋转、矩阵的翻转和矩阵求逆)
  10. 华为路由器忘记密码怎么恢复
  11. SSD(Single Shot MultiBox Detector)原理详解
  12. 使用自开发的代理服务器解决 SAP UI5 FileUploader 上传文件时遇到的跨域访问错误试读版
  13. 10类职业人士最容易受到失眠困扰
  14. Oracle 查询库文件信息
  15. Entity Framework学习笔记——EF简介(一篇文章告诉你什么是EF)
  16. linux如何使用sin函数,Ubuntu下使用make编译c文件,不能调用sin cos 等函数问题的解决...
  17. 班旗怎么用软件设计,(最新整理)班旗设计大赛主持词
  18. iOS内存管理 —— 自动释放池和runloop
  19. 农夫过河——python类穷举法实现
  20. 赶鸭子;角谷定理;java实现

热门文章

  1. 关于c3样式在浏览器上的兼容问题
  2. tuning-primer.sh 性能调试工具的使用
  3. Impala之加载HBase数据
  4. HDFS源码分析DataXceiver之整体流程
  5. openstack 手动安装版 功能测试
  6. Swing编程基础 之三
  7. 程序员创业的两难困境
  8. jq fileupload 设置最大文件大小5m_我猜你并不会设置“分辨率”
  9. Java 并发(JUC 包-02)
  10. pop!_os_Pop!幕后花絮_OS Linux