1.WMI简介
WMI是英文Windows Management Instrumentation的简写,它的功能主要是:访问本地主机的一些信息和服务,可以管理远程计算机(当然你必须要拥有足够的权限),比如:重启,关机,关闭进程,创建进程等。
2.使用时首先添加System.Management.dll,然后引用

using System.Management;
using System.Threading; 
3.示例代码
3.1 html代码
<HTML>
    
<HEAD>
        
<title>WMITest</title>
        
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
        
<meta name="CODE_LANGUAGE" Content="C#">
        
<meta name="vs_defaultClientScript" content="JavaScript">
        
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    
</HEAD>
    
<body MS_POSITIONING="GridLayout">
        
<form id="Form1" method="post" runat="server">
            
<FONT face="宋体">
                
<asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 48px; POSITION: absolute; TOP: 16px" runat="server"
                    Text
="获得本地磁盘的信息" Width="152px"></asp:Button>
                
<asp:Button id="Button2" style="Z-INDEX: 102; LEFT: 32px; POSITION: absolute; TOP: 56px" runat="server"
                    Text
="获得指定磁盘的容量" Width="144px"></asp:Button>
                
<asp:Button id="Button3" style="Z-INDEX: 103; LEFT: 32px; POSITION: absolute; TOP: 96px" runat="server"
                    Text
="列出机器中所有的共享资源" Width="192px"></asp:Button>
                
<asp:Button id="Button4" style="Z-INDEX: 104; LEFT: 8px; POSITION: absolute; TOP: 128px" runat="server"
                    Text
="控制让系统中的某个文件夹共享或取消共享" Width="264px"></asp:Button>
                
<asp:Button id="Button5" style="Z-INDEX: 105; LEFT: 48px; POSITION: absolute; TOP: 160px" runat="server"
                    Text
="获得系统服务的运行状态"></asp:Button>
                
<asp:Button id="Button6" style="Z-INDEX: 106; LEFT: 40px; POSITION: absolute; TOP: 192px" runat="server"
                    Text
="通过WMI修改IP,而实现不用重新启动" Width="248px"></asp:Button>
                
<asp:Button id="Button7" style="Z-INDEX: 107; LEFT: 24px; POSITION: absolute; TOP: 224px" runat="server"
                    Text
="如何利用WMI远程重启远程计算机" Width="232px"></asp:Button>
                
<asp:Button id="Button8" style="Z-INDEX: 108; LEFT: 40px; POSITION: absolute; TOP: 264px" runat="server"
                    Text
="利用WMI创建一个新的进程" Width="192px"></asp:Button>
                
<asp:Button id="Button9" style="Z-INDEX: 109; LEFT: 32px; POSITION: absolute; TOP: 296px" runat="server"
                    Text
="如何通过WMI终止一个进程" Width="192px"></asp:Button>
                
<asp:Button id="Button10" style="Z-INDEX: 110; LEFT: 32px; POSITION: absolute; TOP: 328px" runat="server"
                    Text
="如何用WMI 来获取远程机器的目录以及文件" Width="280px"></asp:Button>
                
<asp:Button id="Button11" style="Z-INDEX: 111; LEFT: 424px; POSITION: absolute; TOP: 24px" runat="server"
                    Text
="网卡的MAC地址" Width="120px"></asp:Button>
                
<asp:Button id="Button12" style="Z-INDEX: 112; LEFT: 456px; POSITION: absolute; TOP: 64px" runat="server"
                    Text
="CPU的系列号 " Width="104px"></asp:Button>
                
<asp:Button id="Button13" style="Z-INDEX: 113; LEFT: 448px; POSITION: absolute; TOP: 120px"
                    runat
="server" Text="主板的系列号"></asp:Button>
                
<asp:Button id="Button14" style="Z-INDEX: 114; LEFT: 472px; POSITION: absolute; TOP: 160px"
                    runat
="server" Text="获取硬盘ID"></asp:Button>
                
<asp:Button id="Button15" style="Z-INDEX: 115; LEFT: 448px; POSITION: absolute; TOP: 208px"
                    runat
="server" Text="获取本机的用户列表" Width="144px"></asp:Button></FONT>
        
</form>
    
</body>
</HTML>
3.2cs代码
public class WMITest : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.Button Button2;
        
protected System.Web.UI.WebControls.Button Button3;
        
protected System.Web.UI.WebControls.Button Button4;
        
protected System.Web.UI.WebControls.Button Button5;
        
protected System.Web.UI.WebControls.Button Button6;
        
protected System.Web.UI.WebControls.Button Button7;
        
protected System.Web.UI.WebControls.Button Button8;
        
protected System.Web.UI.WebControls.Button Button9;
        
protected System.Web.UI.WebControls.Button Button10;
        
protected System.Web.UI.WebControls.Button Button11;
        
protected System.Web.UI.WebControls.Button Button12;
        
protected System.Web.UI.WebControls.Button Button13;
        
protected System.Web.UI.WebControls.Button Button14;
        
protected System.Web.UI.WebControls.Button Button15;
        
protected System.Web.UI.WebControls.Button Button1;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
// Put user code to initialize the page here
        }


        
#region Web Form Designer generated code
        
override protected void OnInit(EventArgs e)
        
{
            
//
            
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
            
//
            InitializeComponent();
            
base.OnInit(e);
        }

        
        
/// <summary>
        
/// Required method for Designer support - do not modify
        
/// the contents of this method with the code editor.
        
/// </summary>

        private void InitializeComponent()
        
{    
            
this.Button1.Click += new System.EventHandler(this.Button1_Click);
            
this.Button2.Click += new System.EventHandler(this.Button2_Click);
            
this.Button3.Click += new System.EventHandler(this.Button3_Click);
            
this.Button4.Click += new System.EventHandler(this.Button4_Click);
            
this.Button5.Click += new System.EventHandler(this.Button5_Click);
            
this.Button6.Click += new System.EventHandler(this.Button6_Click);
            
this.Button7.Click += new System.EventHandler(this.Button7_Click);
            
this.Button8.Click += new System.EventHandler(this.Button8_Click);
            
this.Button9.Click += new System.EventHandler(this.Button9_Click);
            
this.Button10.Click += new System.EventHandler(this.Button10_Click);
            
this.Button11.Click += new System.EventHandler(this.Button11_Click);
            
this.Button12.Click += new System.EventHandler(this.Button12_Click);
            
this.Button13.Click += new System.EventHandler(this.Button13_Click);
            
this.Button14.Click += new System.EventHandler(this.Button14_Click);
            
this.Button15.Click += new System.EventHandler(this.Button15_Click);
            
this.Load += new System.EventHandler(this.Page_Load);

        }

        
#endregion


        
#region 1.如何用WMI获得指定磁盘的容量
        
private string DriveType(string type)
        
{
            
string rtntype="";
            
switch (type)
            
{
                
case "1":
                    rtntype
="Not Type";
                    
break;
                
case "2":
                    rtntype
="Floppy disk";
                    
break;
                
case "3":
                    rtntype
="Hard disk";
                    
break;
                
case "4":
                    rtntype
="Removable drive or network drive";
                    
break;
                
case "5":
                    rtntype
="CD-ROM";
                    
break;
                
case "6":
                    rtntype
="RAM disk";
                    
break;
                
default :
                    
break;
            }

            
return rtntype;
        }


        
private void Button1_Click(object sender, System.EventArgs e)
        
{
            SelectQuery query
=new SelectQuery("Select * From Win32_LogicalDisk"); 
            ManagementObjectSearcher searcher
=new ManagementObjectSearcher(query); 
            
foreach(ManagementBaseObject disk in searcher.Get()) 
            

                Response.Write(disk[
"Name"+" "+DriveType(disk["DriveType"].ToString()) + " " + disk["VolumeName"]+"<br>"); 
            }

        }

        
#endregion


        
#region 2.如何用WMI获得指定磁盘的容量
        
private void Button2_Click(object sender, System.EventArgs e)
        
{
            ManagementObject disk 
= new ManagementObject("win32_logicaldisk.deviceid=\"c:\""); 
            disk.Get(); 
            Response.Write(
"Logical Disk Size = " + disk["Size"+ " bytes");             
        }

        
#endregion


        
#region 3.如何列出机器中所有的共享资源
        
private void Button3_Click(object sender, System.EventArgs e)
        
{
            ManagementObjectSearcher searcher 
= new ManagementObjectSearcher("SELECT * FROM Win32_share"); 
            
foreach (ManagementObject share in searcher.Get()) 
            

                Response.Write(share.GetText(TextFormat.Mof)); 
            }
 
        }

        
#endregion


        
#region 4.怎样写程控制让系统中的某个文件夹共享或取消共享
        
private void Button4_Click(object sender, System.EventArgs e)
        
{
            
/*首先,这需要以有相应权限的用户登录系统才行
            将 
            object[] obj = {"C:\\Temp","我的共享",0,10,"Dot Net 实现的共享",""}; 
            改为 
            object[] obj = {"C:\\Temp","我的共享",0,null,"Dot Net 实现的共享",""}; 
            就可以实现授权给最多用户了。
            
*/

            ManagementClass _class 
= new ManagementClass(new ManagementPath("Win32_Share"));
            
object[] obj = {"C:\\Temp","我的共享",0,10,"Dot Net 实现的共享",""};
            _class.InvokeMethod(
"create",obj); 
        }

        
#endregion


        
#region 5.如何获得系统服务的运行状态
        
private void Button5_Click(object sender, System.EventArgs e)
        
{
            
string[] lvData =  new string[4];            
            ManagementObjectSearcher searcher 
=new ManagementObjectSearcher("SELECT * FROM Win32_Service"); 
            
foreach (ManagementObject mo in searcher.Get()) 
            

                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(); 
                Response.Write(lvData[
0]+lvData[1]+lvData[2]+lvData[3]);                    
            }
             
        }

        
#endregion


        
#region 6.通过WMI修改IP,而实现不用重新启动
        
private void Button6_Click(object sender, System.EventArgs e)
        
{
            ReportIP(); 
            
// SwitchToDHCP(); 
            SwitchToprivate(); 
            Thread.Sleep( 
5000 ); 
            ReportIP(); 
            Response.Write( 
"end." );
        }
        
        
        
private 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

                inPar 
= mo.GetMethodParameters("EnableDHCP"); 
                outPar 
= mo.InvokeMethod( "EnableDHCP", inPar, null ); 
                
break
            }
 
        }
 

        
private void SwitchToprivate() 
        

            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( "Enableprivate" ); 
                inPar[
"IPAddress"= new string[] "192.168.1.1" }
                inPar[
"SubnetMask"= new string[] "255.255.255.0" }
                outPar 
= mo.InvokeMethod( "Enableprivate", inPar, null ); 
                
break
            }
 
        }
 

        
private void ReportIP() 
        

            Response.Write( 
"****** Current IP addresses:" ); 
            ManagementClass mc 
= new ManagementClass("Win32_NetworkAdapterConfiguration"); 
            ManagementObjectCollection moc 
= mc.GetInstances(); 
            
foreach( ManagementObject mo in moc ) 
            

                
if! (bool) mo[ "IPEnabled" ] ) 
                    
continue

                
string str="{0}\n SVC: '{1}' MAC: [{2}]";
                str
= string.Format(mo["Caption"].ToString(), mo["ServiceName"].ToString(),mo["MACAddress"].ToString());

                Response.Write(str); 

                
string[] addresses = (string[]) mo[ "IPAddress" ]; 
                
string[] subnets = (string[]) mo[ "IPSubnet" ]; 

                Response.Write( 
" Addresses :" ); 
                
foreach(string sad in addresses) 
                    Response.Write(sad
+"<br>"); 

                Response.Write( 
" Subnets :" ); 
                
foreach(string sub in subnets ) 
                    Response.Write(sub
+"<br>"); 
            }
 
        }

        
#endregion


        
#region 7.如何利用WMI远程重启远程计算机
        
private void Button7_Click(object sender, System.EventArgs e)
        
{
            Response.Write(
"Computer details retrieved using Windows Management Instrumentation (WMI)"); 
            Response.Write(
"mailto:singlepine@hotmail.com"); 
            Response.Write(
"=========================================================================");  
            
//连接远程计算机 
            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); 
                Response.Write(mo.ToString()); 
            }
 
        }

        
#endregion


        
#region 8.利用WMI创建一个新的进程
        
private void Button8_Click(object sender, System.EventArgs e)
        
{
            
//Get the object on which the method will be invoked 
            ManagementClass processClass = new ManagementClass("Win32_Process"); 

            
//Get an input parameters object for this method 
            ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); 

            
//Fill in input parameter values 
            inParams["CommandLine"= "calc.exe"

            
//Execute the method 
            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 
            Response.Write("Creation of calculator process returned: " + outParams["returnvalue"]); 
            Response.Write(
"Process ID: " + outParams["processId"]); 

        }

        
#endregion


        
#region 9.如何通过WMI终止一个进程
        
private void Button9_Click(object sender, System.EventArgs e)
        
{
            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);

            Response.Write(
"Return Status = " + outParams["Returnvalue"]);
        }

        
#endregion


        
#region 10.如何用WMI 来获取远程机器的目录以及文件
        
private void Button10_Click(object sender, System.EventArgs e)
        
{
            ManagementObject disk 
= new ManagementObject(

                
"win32_logicaldisk.deviceid=\"c:\"");

            disk.Get();

            Response.Write(
"Logical Disk Size = " + disk["Size"+ " bytes");
        }

        
#endregion


        
#region 11.网卡的MAC地址
        
private void Button11_Click(object sender, System.EventArgs e)
        
{
            ManagementClass mc 
= new ManagementClass("Win32_NetworkAdapterConfiguration"); 
            ManagementObjectCollection moc 
= mc.GetInstances(); 
            
foreach(ManagementObject mo in moc) 
            

                
if((bool)mo["IPEnabled"== true
                    Response.Write(
"MAC address"+mo["MacAddress"].ToString()+"<br>"); 
                mo.Dispose(); 
            }
 
        }

        
#endregion


        
#region 12.CPU的系列号 
        
private void Button12_Click(object sender, System.EventArgs e)
        
{
            
string cpuInfo = "";//cpu序列号 
            ManagementClass cimobject = new ManagementClass("Win32_Processor"); 
            ManagementObjectCollection moc 
= cimobject.GetInstances(); 
            
foreach(ManagementObject mo in moc) 
            

                cpuInfo 
= mo.Properties["ProcessorId"].Value.ToString(); 
                Response.Write(cpuInfo);
            }
 
        }

        
#endregion


        
#region 13.主板的系列号
        
private void Button13_Click(object sender, System.EventArgs e)
        
{
            ManagementObjectSearcher searcher
=new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
            
foreach(ManagementObject share in searcher.Get())
            
{
                Response.Write(
"主板制造商:" + share["Manufacturer"].ToString()) ;
                Response.Write(
"型号:" +share["Product"].ToString()) ;
                Response.Write(
"序列号:"+share["SerialNumber"].ToString()) ;
            }

        }

        
#endregion


        
#region 14.获取硬盘ID
        
private void Button14_Click(object sender, System.EventArgs e)
        
{
            String HDid; 
            ManagementClass cimobject 
= new ManagementClass("Win32_DiskDrive"); 
            ManagementObjectCollection moc 
= cimobject.GetInstances(); 
            
foreach(ManagementObject mo in moc) 
            

                HDid 
= (string)mo.Properties["Model"].Value; 
                Response.Write(HDid);  
            }
 
        }

        
#endregion


        
#region 15.获取本机的用户列表
        
private void Button15_Click(object sender, System.EventArgs e)
        
{
            SelectQuery query 
= new SelectQuery("SELECT * FROM Win32_UserAccount");
            ManagementObjectSearcher searcher 
= new ManagementObjectSearcher(query);
            
foreach(ManagementObject os in searcher.Get())
            
{
                Response.Write(os[
"Name"]);
            }

        }

        
#endregion

    }
Posted on 2008-07-02 10:09  hesen  阅读(486)  评论(0编辑  收藏  举报