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

C# 实现 Hyper-V 虚拟机 管理,布布扣,bubuko.com

时间: 2024-10-14 05:50:14

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

win8/win10 自带Hyper V虚拟机

为什么是hyperV而不是vmware workstation或者virturalBox? 萝卜白菜,各有所爱.这里不比较数据,不深究技术,我选择的理由很简单:系统自带,不用安装额外的软件,而且性能也还可以. hyperV最早集成于win8中,win7及更老版本是没有此功能的.打开"任务管理器",在"性能"选项卡"虚拟化"中可到启用状态.可在BIOS设备.安全或CPU选项卡中找到虚拟化选项. BIOS中开启硬件支持后,可在"添加删除程序

Hyper - V (四)

安装虚拟机 新建虚拟机 为新建的虚拟机起名,默认保存路径为前面设置的默认路径 指定虚拟机内存大小 指定虚拟机网卡连接到外部网络还是内部网络(或专用网络) 创建虚拟硬盘,指定硬盘存储路径及硬盘大小 选择安装文件的引导路径,支持光盘安装,ISO安装等方式. 这里我们选择通过光驱引导的方式来安装系统 完成虚拟机设置. 右键点击新建的虚拟机,设置可以更改虚拟机的配置选项. 将ISO文件加载到虚拟机中,即可以实现光盘引导功能. 启动虚拟机-- 安装系统 Hyper - V (四),布布扣,bubuko.c

Hyper - V (三)

创建内部网络及专用网络 内部网络:不与外部通讯的网络,仅与物理机及虚拟机之间通讯. 专用网络:不与外部及物理机通讯的网络,仅支持虚拟机之间的通讯. 添加内部网络 单击虚拟网络管理器 2. 点击新建虚拟网络 -- 内部 -- 添加 3. 此时将新建立一个内部的虚拟网卡 在添加内网通信的IP地址即可. Hyper - V (三),布布扣,bubuko.com

Hyper v 单网卡 外部网络

先说一下环境: WIN 8.1 单网卡(有 无线 和 有线网卡, 但是没有多余的网络接口可插,还是等于单网卡) Hyper V 有3种虚拟交换机类型: 专用 / 内部 / 外部 各有各的用处, 我理解也不多,不多嘴误导大家. 今天说这个,是因为要做CSS和JS兼容调试, 开发用的都是IE11,用IE11的调试工具将文档模式调为 IE8 ,发现 jQuery.Validation 不能常运行. 但是用虚拟机装的 XP上直接用IE8 ,却没有任何问题,真的很蛋疼. 工作用的有两台电脑,一台装的是WI

Hyper - V (六)安装Hyper - V系统集成服务

安装Hyper - V系统集成服务 作用: 操作系统关闭 -- 当物理机关机时,Hyper - V 上的虚拟机将先于物理机关机.如不安装此服务,虚拟机将不会自动关机而造成类似于直接断电. 时间同步 -- 即虚拟机与物理机的时间同步 数据交换 -- 物理机可以查看到虚拟机的相关信息 ,如计算机名等 检测信号 -- 当虚拟机假死或无响应状态时,虚拟机会发送重启等信号 备份(卷快照) -- 开启备份功能 如何安装: 点击操作 --  插入集成服务安装盘 点击安装即可,安装完毕后重启 Hyper - V

虚拟机管理额外作业

虚拟机管理额外作业: 编写一个脚本,可以用来执行"删除,正常关闭,强行关闭,临时开启,永久开启,删除虚拟机管理"的操作. [[email protected] Desktop]# vim vm-manager 实验效果:

xen虚拟机管理命令

#xen虚拟机管理命令 xm list:所有已知的虚拟机列表 xm create:启动一个非托管的虚拟机 xm top:提供所有虚拟机的状态概貌 xm console:打开控制台管理虚拟机 xm new:添加虚拟机到Xenbase托管环境 xm start:从Xenbase托管环境启动虚拟机 xm destroy:像关掉电源那样关闭虚拟机 xm shutdown:正确地关掉虚拟机 xm reboot:重新启动虚拟机 xm pause:暂停虚拟机的活动而不释放使用的内存资源 xm unpause:

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

转载自:http://mabofeng.blog.51cto.com/2661587/1019497 在上一博文中我们安装了强大的VMware vCenter管理中心,通过VMware vSphere Client连接到VMware vCenter管理中心, vSphere 的两个核心组件是 VMware ESXi 和 VMware vCenter Server.ESXi 是用于创建和运行虚拟机的虚拟化平台.vCenter Server 是一种服务,充当连接到网络的 ESXi 主机的中心管理员.

linux下虚拟机管理

##linux下虚拟机管理## $rht-vmctl start desktop        ###启动虚拟机Desktop $rht-vmctl view  desktop        ##显示虚拟机界面 $rht-vmctl stop desktop         ##正常关闭虚拟机 $rht-vmctl poweroff desktop     ##强制关机 $rht-vmctl reser desktop        ##重置虚拟机 $rht-vmctl fullreset de