WMI使用技巧
很多的朋友对
WMI
可能见过但理解不深,我也是十分想了解关于
WMI
的知识,可一直找不对太合适的资料,在网上的一些资料不是有很多错误,就是讲解不清,我有空的时候将关于
WMI
的知识集中一下,放在这里便于大家学习。本贴会不断增加。
1
、
什么是
WMI
WMI
是英文
Windows Management Instrumentation
的简写,它的功能主要是:访问本地主机的一些信息和服务,可以管理远程计算机(当然你必须要拥有足够的权限),比如:重启,关机,关闭进程,创建进程等。
2
、
如何用
WMI
获得本地磁盘的信息?
首先要在
VS.NET
中创建一个项目,然后在添加引用中引用一个
.net
的装配件:
System.Management.dll,
这样你的项目才能使用
WMI
。代码如下:
using System;
using System.Management;
class Sample_ManagementObject
{
public static int Main(string[] args)
{
SelectQuery query=new SelectQuery("Select * From Win32_LogicalDisk");
ManagementObjectSearcher searcher=new ManagementObjectSearcher(query);
foreach(ManagementBaseObject disk in searcher.Get())
{
Console.WriteLine("/r/n"+disk["Name"] +" "+disk["DriveType"] + " " + disk["VolumeName"]);
}
Console.ReadLine();
using System.Management;
class Sample_ManagementObject
{
public static int Main(string[] args)
{
SelectQuery query=new SelectQuery("Select * From Win32_LogicalDisk");
ManagementObjectSearcher searcher=new ManagementObjectSearcher(query);
foreach(ManagementBaseObject disk in searcher.Get())
{
Console.WriteLine("/r/n"+disk["Name"] +" "+disk["DriveType"] + " " + disk["VolumeName"]);
}
Console.ReadLine();
return 0;
}
}
disk["DriveType"]
的返回值意义如下
:
1 No type
2 Floppy disk
3 Hard disk
4 Removable drive or network drive
5 CD-ROM
6 RAM disk
2 Floppy disk
3 Hard disk
4 Removable drive or network drive
5 CD-ROM
6 RAM disk
3
、如何用
WMI
获得指定磁盘的容量?
using System;
using System.Management;
using System.Management;
// This example demonstrates reading a property of a ManagementObject.
class Sample_ManagementObject
{
public static int Main(string[] args)
{
ManagementObject disk = new ManagementObject(
"win32_logicaldisk.deviceid=/"c:/"");
disk.Get();
Console.WriteLine("Logical Disk Size = " + disk["Size"] + " bytes");
Console.ReadLine();
return 0;
}
}
class Sample_ManagementObject
{
public static int Main(string[] args)
{
ManagementObject disk = new ManagementObject(
"win32_logicaldisk.deviceid=/"c:/"");
disk.Get();
Console.WriteLine("Logical Disk Size = " + disk["Size"] + " bytes");
Console.ReadLine();
return 0;
}
}
4
、
如何列出机器中所有的共享资源?
using System;
using System.Management;
using System.Management;
class TestApp {
[STAThread]
static void Main()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher(
"SELECT * FROM Win32_share");
foreach (ManagementObject share in searcher.Get())
{
Console.WriteLine(share.GetText(TextFormat.Mof));
}
}
}
别忘记在引用中把 System.Management 添加进来。
[STAThread]
static void Main()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher(
"SELECT * FROM Win32_share");
foreach (ManagementObject share in searcher.Get())
{
Console.WriteLine(share.GetText(TextFormat.Mof));
}
}
}
别忘记在引用中把 System.Management 添加进来。
5
、
怎样写程控制让系统中的某个文件夹共享或取消共享
.
?
首先,这需要以有相应权限的用户登录系统才行。然后,试试下面的代码:
using System;
using System.Management;
using System.Management;
class CreateShare
{
public static void Main(string[] args)
{
ManagementClass _class = new ManagementClass(new ManagementPath("Win32_Share"));
{
public static void Main(string[] args)
{
ManagementClass _class = new ManagementClass(new ManagementPath("Win32_Share"));
object[] obj = {"C://Temp","
我的共享
",0,10,"Dot Net
实现的共享
",""};
_class.InvokeMethod("create",obj);
}
}
将
}
}
将
object[] obj = {"C://Temp","
我的共享
",0,10,"Dot Net
实现的共享
",""};
改为
object[] obj = {"C://Temp","
我的共享
",0,null,"Dot Net
实现的共享
",""};
就可以实现授权给最多用户了。
6
、
如何获得系统服务的运行状态?
private void getServices()
{
ManagementObjectCollection queryCollection;
string[] lvData = new string[4];
try
{
queryCollection = getServiceCollection("SELECT * FROM Win32_Service");
foreach ( ManagementObject mo in queryCollection)
{
//create child node for operating system
lvData[0] = mo["Name"].ToString();
lvData[1] = mo["StartMode"].ToString();
if (mo["Started"].Equals(true))
lvData[2] = "Started";
else
lvData[2] = "Stop";
lvData[3] = mo["StartName"].ToString();
//create list item
ListViewItem lvItem = new ListViewItem(lvData,0);
listViewServices.Items.Add(lvItem);
}
}
catch (Exception e)
{
MessageBox.Show("Error: " + e);
}
}
{
ManagementObjectCollection queryCollection;
string[] lvData = new string[4];
try
{
queryCollection = getServiceCollection("SELECT * FROM Win32_Service");
foreach ( ManagementObject mo in queryCollection)
{
//create child node for operating system
lvData[0] = mo["Name"].ToString();
lvData[1] = mo["StartMode"].ToString();
if (mo["Started"].Equals(true))
lvData[2] = "Started";
else
lvData[2] = "Stop";
lvData[3] = mo["StartName"].ToString();
//create list item
ListViewItem lvItem = new ListViewItem(lvData,0);
listViewServices.Items.Add(lvItem);
}
}
catch (Exception e)
{
MessageBox.Show("Error: " + e);
}
}
7
、
通过
WMI
修改
IP
,而实现不用重新启动?
using System;
using System.Management;
using System.Threading;
using System.Management;
using System.Threading;
namespace WmiIpChanger
{
class IpChanger
{
[MTAThread]
static void Main(string[] args)
{
ReportIP();
// SwitchToDHCP();
SwitchToStatic();
Thread.Sleep( 5000 );
ReportIP();
Console.WriteLine( "end." );
}
{
class IpChanger
{
[MTAThread]
static void Main(string[] args)
{
ReportIP();
// SwitchToDHCP();
SwitchToStatic();
Thread.Sleep( 5000 );
ReportIP();
Console.WriteLine( "end." );
}
static void SwitchToDHCP()
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo["IPEnabled"] )
continue;
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo["IPEnabled"] )
continue;
inPar = mo.GetMethodParameters("EnableDHCP");
outPar = mo.InvokeMethod( "EnableDHCP", inPar, null );
break;
}
}
outPar = mo.InvokeMethod( "EnableDHCP", inPar, null );
break;
}
}
static void SwitchToStatic()
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue;
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue;
inPar = mo.GetMethodParameters( "EnableStatic" );
inPar["IPAddress"] = new string[] { "192.168.1.1" };
inPar["SubnetMask"] = new string[] { "255.255.255.0" };
outPar = mo.InvokeMethod( "EnableStatic", inPar, null );
break;
}
}
inPar["IPAddress"] = new string[] { "192.168.1.1" };
inPar["SubnetMask"] = new string[] { "255.255.255.0" };
outPar = mo.InvokeMethod( "EnableStatic", inPar, null );
break;
}
}
static void ReportIP()
{
Console.WriteLine( "****** Current IP addresses:" );
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue;
{
Console.WriteLine( "****** Current IP addresses:" );
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach( ManagementObject mo in moc )
{
if( ! (bool) mo[ "IPEnabled" ] )
continue;
Console.WriteLine( "{0}/n SVC: '{1}' MAC: [{2}]", (string) mo["Caption"],
(string) mo["ServiceName"], (string) mo["MACAddress"] );
(string) mo["ServiceName"], (string) mo["MACAddress"] );
string[] addresses = (string[]) mo[ "IPAddress" ];
string[] subnets = (string[]) mo[ "IPSubnet" ];
string[] subnets = (string[]) mo[ "IPSubnet" ];
Console.WriteLine( " Addresses :" );
foreach(string sad in addresses)
Console.WriteLine( "/t'{0}'", sad );
foreach(string sad in addresses)
Console.WriteLine( "/t'{0}'", sad );
Console.WriteLine( " Subnets :" );
foreach(string sub in subnets )
Console.WriteLine( "/t'{0}'", sub );
}
}
}
}
foreach(string sub in subnets )
Console.WriteLine( "/t'{0}'", sub );
}
}
}
}
8
、
如何利用
WMI
远程重启远程计算机?
using System;
using System.Management;
namespace WMI3
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
Console.WriteLine("Computer details retrieved using Windows Management Instrumentation (WMI)");
Console.WriteLine("mailto:Written%<st1:chsdate w:st="on" IsROCDate="False" IsLunarDate="False" Day="2" Month="1" Year="2002">2002/01/02%20By%20John%20O'Donnell%20-%20csharpconsulting@hotmail.com");
Console.WriteLine("========================================
=================================");
// 连接远程计算机
ConnectionOptions co = new ConnectionOptions();
co.Username = "john";
co.Password = "john";
System.Management.ManagementScope ms = new System.Management.ManagementScope("192.168.1.2//root//cimv2", co);
// 查询远程计算机
System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection1 = query1.Get();
foreach( ManagementObject mo in queryCollection1 )
{
string[] ss={""};
mo.InvokeMethod("Reboot",ss);
Console.WriteLine(mo.ToString());
}
}
}
}
using System;
using System.Management;
namespace WMI3
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
Console.WriteLine("Computer details retrieved using Windows Management Instrumentation (WMI)");
Console.WriteLine("mailto:Written%<st1:chsdate w:st="on" IsROCDate="False" IsLunarDate="False" Day="2" Month="1" Year="2002">2002/01/02%20By%20John%20O'Donnell%20-%20csharpconsulting@hotmail.com");
Console.WriteLine("========================================
=================================");
// 连接远程计算机
ConnectionOptions co = new ConnectionOptions();
co.Username = "john";
co.Password = "john";
System.Management.ManagementScope ms = new System.Management.ManagementScope("192.168.1.2//root//cimv2", co);
// 查询远程计算机
System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms,oq);
ManagementObjectCollection queryCollection1 = query1.Get();
foreach( ManagementObject mo in queryCollection1 )
{
string[] ss={""};
mo.InvokeMethod("Reboot",ss);
Console.WriteLine(mo.ToString());
}
}
}
}
9
、利用
WMI
创建一个新的进程?
using System;
using System.Management;
using System.Management;
// This sample demonstrates invoking a WMI method using parameter objects
public class InvokeMethod
{
public static void Main()
{
public class InvokeMethod
{
public static void Main()
{
//Get the object on which the method will be invoked
ManagementClass processClass = new ManagementClass("Win32_Process");
ManagementClass processClass = new ManagementClass("Win32_Process");
//Get an input parameters object for this method
ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
//Fill in input parameter values
inParams["CommandLine"] = "calc.exe";
inParams["CommandLine"] = "calc.exe";
//Execute the method
ManagementBaseObject outParams = processClass.InvokeMethod ("Create", inParams, null);
ManagementBaseObject outParams = processClass.InvokeMethod ("Create", inParams, null);
//Display results
//Note: The return code of the method is provided in the "returnvalue" property of the outParams object
Console.WriteLine("Creation of calculator process returned: " + outParams["returnvalue"]);
Console.WriteLine("Process ID: " + outParams["processId"]);
}
}
//Note: The return code of the method is provided in the "returnvalue" property of the outParams object
Console.WriteLine("Creation of calculator process returned: " + outParams["returnvalue"]);
Console.WriteLine("Process ID: " + outParams["processId"]);
}
}
10
、
如何通过
WMI
终止一个进程?
using System;
using System.Management;
using System.Management;
// This example demonstrates how to stop a system service.
class Sample_InvokeMethodOptions
{
public static int Main(string[] args) {
ManagementObject service =
new ManagementObject("win32_service=/"winmgmt/"");
InvokeMethodOptions options = new InvokeMethodOptions();
options.Timeout = new TimeSpan(0,0,0,5);
class Sample_InvokeMethodOptions
{
public static int Main(string[] args) {
ManagementObject service =
new ManagementObject("win32_service=/"winmgmt/"");
InvokeMethodOptions options = new InvokeMethodOptions();
options.Timeout = new TimeSpan(0,0,0,5);
ManagementBaseObject outParams = service.InvokeMethod("StopService", null, options);
Console.WriteLine("Return Status = " + outParams["Returnvalue"]);
return 0;
}
}
}
}
11
、
如何用
WMI
来获取远程机器的目录以及文件
.
比如如何列出一个目录下的所有文件
,
或者所有子目录
;
如何删除
,
舔加
,
更改文件
?
using System;
using System.Management;
using System.Management;
// This example demonstrates reading a property of a ManagementObject.
class Sample_ManagementObject
{
public static int Main(string[] args) {
ManagementObject disk = new ManagementObject(
"win32_logicaldisk.deviceid=/"c:/"");
disk.Get();
Console.WriteLine("Logical Disk Size = " + disk["Size"] + " bytes");
return 0;
}
}
12 、 参考资料
可以参考下列内容:
msdn WMI SDK:
us/wmisdk/wmi/wmi_start_page.asp http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/wmisdk/wmi/wmi_start_page.asp http://msdn.microsoft.com/library/default.asp?url=/library/en-
WMI
使用说明(
csdn
)
:
http://www.csdn.net/develop/article/15/15346.shtm
http://www.csdn.net/develop/article/15/15346.shtm
WMI
技术的应用
for .net
(
csdn
)
:
http://www.csdn.net/develop/article/16/16419.shtm
http://www.csdn.net/develop/article/16/16419.shtm
在
.NET
中轻松获取系统信息
(1)
-
WMI
篇(
csdn
)
:
http://www.csdn.net/develop/article/15/15744.shtm
http://www.csdn.net/develop/article/15/15744.shtm
:)