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;        }    }}

 

时间: 2025-01-29 15:21:00

C# 实现 Hyper-V 虚拟机 管理的相关文章

windows server 2012 中的Hyper V

问题描述 windows server 2012 中的Hyper V windows server 2012 中的Hyper V,断电时虚拟机无故启动不了.怎么解决呢? 解决方案 这个不好说,虚拟机相当于一个独立的计算机,任何软件故障都可能导致无法启动. 重新做一个虚拟机,不安装别的软件看看是否正常. 解决方案二: 问题是没有安装任何软件,是做域控用的.很多时候,断电或者按开机键开机就会无故启动不了.有域账号在,重装严重呀.谢谢你的回答. 解决方案三: 断点可能造成系统损坏了.需要repaire

什么是虚拟机管理器

虚拟机管理器(VMM)是Windows 95的实际操作系统,它建立和维护一个管理虚拟机的框架,同时为其他vxd程序提供许多重要的服务.其中三种重要的服务是: 内存管理 中断处理 线程调度 内存管理VMM使用Intel 80386或更新的处理器的内存调页能力来为系统虚拟机创建一个32位的虚地址空间.它把这个地址空间分为四个不同的部分: V86区 地址从0H到10FFEFH,这个区属于当前执行的虚拟机. 应用程序私有区地址从4MB到2GB.这是Win32应用程序运行的空间.每个Win32的进程都有它

[原]LVM管理与虚拟机管理

一.装机及配置: 如何做raid,装OS等此处略过,从网络配置开始: 两种方法: 方法1.如下,桥接模式 auto lo iface lo inet loopback auto eth0 iface eth0 inet static address 192.168.××.×× netmask 255.255.255.0 gateway 192.168.××.1 broadcast 192.168.××.255 auto eth1 iface eth1 inet static address **

云计算构建基石之Hyper-V:虚拟机管理

本文讲的是云计算构建基石之Hyper-V:虚拟机管理,作为云计算的重要基石,虚拟化技术的好坏起着关键作用.Hyper-V作为微软重要的虚拟化解决技术,在微软云计算构建解决方案中,更是关键至关键,基础之基础.在本系列文章中,我们向大家介绍Microsoft最新的Hyper-V Server 2008 R2 SP1.Windows Server 2008 R2 SP1做虚拟化主机.用SCVMM 2008 R2 SP1进行管理,主要内容包括: (1) 概述:是选择Windows Server 2008

RHCSA 系列(十五): 虚拟化基础和使用 KVM 进行虚拟机管理

假如你在词典中查一下单词 "虚拟化virtualize",你将会发现它的意思是 "创造某些事物的一个虚拟物(而非真实的)".在计算机行业中,术语虚拟化virtualization指的是:在相同的物理(硬件)系统上,同时运行多个操作系统,且这几个系统相互隔离的可能性,而那个硬件在虚拟化架构中被称作宿主机host. RHCSA 系列: 虚拟化基础和使用 KVM 进行虚拟机管理 – Part 15 通过使用虚拟机监视器(也被称为虚拟机管理程序hypervisor),虚拟机

虚拟机管理:如何在实践中做好数据中心资源平衡

现今对数据中心的要求是稳固.有效,这首先要做到"合理使用".虽然闲置资源对于一个环境来讲是种资金浪费.但若是没能对频繁使用的数据中心进行合理的资源配置,必将引发危险场景.单一硬件失灵可能导致其他物理主机发生故障.IT管理人员面临的困难在于:使用并管理好遍布整个环境的计算资源(通常包括物理的,虚拟的和云资源).本文将和大家讨论作为达到资源优化这一目的所使用的手段--资源规划和问题缓解.我们还将说明如何在问题恶化之前解决它. 资源规划的最佳实践 当今,几乎所有的数据中心都已经拥有或是将会进

技术解析:基于Perl的VMWare虚拟机管理

本文讲的是 :  技术解析:基于Perl的VMWare虚拟机管理  , [IT168技术]众所周知,VMWare在虚拟化和云计算基础架构领域处于全球领先地位,所提供的经客户验证的解决方案可通过降低复杂性以及更灵活.敏捷地交付服务来提高IT效率.而旗下的VMWare vSphere是一整套虚拟化应用产品,它包含VMWare ESX Server.VMWare Virtual Center.VMotion,以及例如VMWare HA.VMWare DRS和VMWare统一备份服务等分布式服务.它提供

Archipel beta 3.2 虚拟机管理工具

Archipel 是一个虚拟机管理和监控的实用工具.它提供了一个集中式的http://www.aliyun.com/zixun/aggregation/13848.html">管理模式,不管是本机还是成千上万个的数据中心的虚拟机,都可以通过Archipel来轻松的管理.您可以使用支持libvirt来管理虚拟化引擎,包括:KVM,Xen,OpenVZ,或VMWare.它可以执行所有基本的虚拟化命令和许多其他的东西,比如live migration,VMCasts,packages等等.Arc

ubuntu安装KVM虚拟机管理virt-manager

打算学习KVM的图形界面管理器virt-manager,但是virt-manager只有linux系统的,没有windows下的.所以只能使用linux桌面系统,在此我选择的是ubuntu系统. 有关ubuntu系统的安装我就不做介绍,下面就介绍有关virt-manager的安装与配置. 其中安装virt-manager的机器不一定要支持虚拟化. 注意virt-manager既有图形界面,也有命令行. 启动ubuntu,并安装virt-manager及其相关的软件.如下图: 首先使用apt-ge