Windows Management Instrumentation (WMI: windows管理规范)
首先来看一段码:
ManagementScope Conn = new ManagementScope("\\\\" + textBox1.Text + "\\root\\cimv2", options); Conn.Connect(); ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher query1 = new ManagementObjectSearcher(Conn, oq); ManagementObjectCollection queryCollection1 = query1.Get(); foreach (ManagementObject mo in queryCollection1) { string[] ss = { "" }; //执行重启操作 if (operationstr.Text == "重新启动") { mo.InvokeMethod("Reboot", ss); } }
|
这是一段运程操作计算机的代码,看了这段码感觉如何,是不是感觉像在操作数据库,其实这一切都得义于我们今天所要说的主题———WMI。
在经过了两天的研究后终于对WMI有了一些了解,由于本人对WMI了解的也不很深入,所以本文只会在浅层面进解析,仅起到抛砖引玉的作用,还望多切入进行更深入的探讨。
WMI是Windows 2K/XP管理系统的核心;对于其他的Win32操作系统,WMI是一个有用的插件。WMI以CIMOM为基础,CIMOM即公共信息模型对象管理器(Common Information Model Object Manager),是一个描述操作系统构成单元的对象数据库,为MMC和脚本程序提供了一个访问操作系统构成单元的公共接口。有了WMI,工具软件和脚本程序访问操作系统的不同部分时不需要使用不同的API;相反,操作系统的不同部分都可以插入WMI,如图一所示(该图来自MSDN),工具软件和WMI可以方便地读写WMI。(摘自:用WMI实现Windows系统自动管理)
图一
WMI工具软件:Windows Management Instrumentation (WMI) SDK
通过Windows Management Instrumentation Extensions for Microsoft Visual Studio .NET 2003 Server Explorer工具可以使用VS2003轻松的对WMI进行编程。
Windows Management Instrumentation (WMI) Tools工具可以方便地查看可用的CIM和Win32类
好了,回到我们刚才的例子,我们来进行分析。
首先我们创建了ManagementScope的instance,表示使用指定选项初始化 ManagementScope 类的、表示指定范围路径的新实例。
Conn.Connect();不用多说,就是打开对象连接。
接着,又构造了一个ObjectQuery对象,并传入了一个字符串,关键是在这个字符串,它看起来像Trance-SQL语句,但是,它其实就是WMI了。如上图所示,我们代码所处的位置在[win32 subsystem],把WMI比作SQL数据库,这个Win32_OperatingSystem类就相当于数据库中的表了。这样理解就简单了吧,不过实际理论要理解清楚。
好了,下面我们就要实例化查询对象——ManagementObjectSearcher了。数据库操作过吧,一样的,传递个连接对象和查询对象,就OK了。
ManagementObjectSearcher.Get()方法是调用指定的 WMI 查询并返回结果集合。
然后是递归循还读取返回结果并进行操作,要说的是InvokeMethod方法。
其方法原型为:
public Object InvokeMethod ( string methodName,//要操作的方法名 Object[] args//包含参数值的数组 )//该方法返回对象值 |
好了大体都差不多了,最后要说的是Win32_OperatingSystem类。
Win32_OperatingSystem类为原生API函数(用脚本对WMI编程不能直接访问Win32 API)
具体方法有(摘自:MSDN Library for Visual Studio 2005)
Reboot |
Class method that shuts down the computer system, and then restarts it. |
SetDateTime |
Class method that allows setting the computer date and time. |
Shutdown |
Class method that unloads programs and DLLs to the point where it is safe to turn off the computer. |
Win32Shutdown |
Class method that provides the full set of shutdown options supported by Windows operating systems. |
下面我们看个MSDN上的例子
using System; using System.Management; public class InvokeMethod { public static void Main() { ManagementClass processClass = new ManagementClass("Win32_Process"); object[] methodArgs = {"notepad.exe", null, null, 0}; object result = processClass.InvokeMethod("Create", methodArgs); Console.WriteLine("Creation of process returned: " + result); Console.WriteLine("Process id: " + methodArgs[3]); } } |
最后,我来对我们的例子作个简单的总结:通过WMI使得我们操作运程计算机可以像操作数据库一样简单,需要的步骤有:
1. 创建连接对象;
2. 打开连接对象;
3. 创建连接通道对象;
4. 用连接对象和连接通道对象构造查询;
5. 获取查询结果;
6. 具体操作。
作品:利用WMI控制远程计算机
附:参考资料
《MSDN Library for Visual Studio 2005》
WMI CIM Studio