WMI ABC

WMI使用技巧集
 很多的朋友對WMI可能見過但理解不深,我也是十分想了解關於WMI的知識,可一直找不對太合適的資料,在網上的一些資料不是有很多錯誤,就是講解不清,我有空的候將關於WMI的知識集中一下,放在這裏便於大家學習。本貼會不斷增加。
1、 什麼是WMI
WMI是英文Windows Management Instrumentation的簡寫,它的功能主要是:訪問本地主機的一些信息和服務,可以管理遠程計算機(當然你必須要擁有足夠的權限),比如:重啓,關機關閉進程,創建進程等。
2、 如何用WMI獲得本地磁盤的信息?
首先要在VS.NET中創建一個項目,然後在添加引用中引用一個.net的裝配件:System.Management.dll,這樣你的項目才能使用WMI。代碼如下:
using System;
using System.Management;

classSample_ManagementObject
{
 public static int Main(string[] args)
 {
  SelectQuery query=new SelectQuery("Select * FromWin32_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


3、如何用WMI獲得指定磁盤的容量?
using System;
using System.Management;

// This exampledemonstrates 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;
 }
}


4、 如何列出機器中所有的共享資源?
using System;
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添加進來。


5、 怎樣寫程控制讓系統中的某個文件夾共享或取消共享.?
首先,這需要以有相應權限的用戶登錄系統才行。然後,試試下面的代碼:
using System;
using System.Management;

class CreateShare
{
 public static void Main(string[] args)
 {
  ManagementClass _class = new ManagementClass(newManagementPath("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,"DotNet 實現的共享",""};
就可以實現授權給最多用戶了。


6、 如何獲得系統服務的運行狀態?
private void getServices()
{
 ManagementObjectCollection queryCollection;
 string[] lvData =  new string[4];
 
 try
 {
  queryCollection = getServiceCollection("SELECT * FROMWin32_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;

namespace WmiIpChanger
{
 class IpChanger
 {
  [MTAThread]
  static void Main(string[] args)
  {
   ReportIP();
   // SwitchToDHCP();
   SwitchToStatic();
   Thread.Sleep( 5000 );
   ReportIP();
   Console.WriteLine( "end." );
  }

  static voidSwitchToDHCP()
  {
   ManagementBaseObject inPar = null;
   ManagementBaseObject outPar = null;
   ManagementClass mc = newManagementClass("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;
   }
  }

  static voidSwitchToStatic()
  {
   ManagementBaseObject inPar = null;
   ManagementBaseObject outPar = null;
   ManagementClass mc = newManagementClass("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;
   }
  }

  static voidReportIP()
  {
   Console.WriteLine( "****** Current IP addresses:" );
   ManagementClass mc = newManagementClass("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[] addresses = (string[]) mo[ "IPAddress" ];
    string[] subnets = (string[]) mo[ "IPSubnet" ];

   Console.WriteLine( " Addresses :" );
    foreach(string sad in addresses)
     Console.WriteLine( "\t'{0}'", sad );

   Console.WriteLine( " Subnets :" );
    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 voidMain(string[] args)
            {
                 Console.WriteLine("Computer details retrieved using Windows ManagementInstrumentation (WMI)");
                 Console.WriteLine("mailto:Written%2002/01/02%20By%20John%20O'Donnell%20-%[email protected]");
                 Console.WriteLine("========================================
=================================");
                  //連接遠程計算機
            ConnectionOptionsco = new ConnectionOptions();
            co.Username= "john";
            co.Password= "john";
           System.Management.ManagementScope ms = newSystem.Management.ManagementScope("\\\\192.168.1.2\\root\\cimv2",co);     
                 //查詢遠程計算機
          System.Management.ObjectQuery oq = newSystem.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem");
                 
          ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms,oq);
           ManagementObjectCollectionqueryCollection1 =query1.Get();           
                 foreach( ManagementObject mo in queryCollection1 )
                 {
                       string[] ss={""};
                       mo.InvokeMethod("Reboot",ss);
                       Console.WriteLine(mo.ToString());
                 }
            }
      }


9、 利用WMI創建一個新的進程?
using System;
using System.Management;

// This sampledemonstrates invoking a WMI method using parameter objects
public class InvokeMethod
{   
 public static void Main()
 {

  //Get the object onwhich the method will be invoked
  ManagementClass processClass = newManagementClass("Win32_Process");

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

  //Fill in inputparameter values
  inParams["CommandLine"] = "calc.exe";

  //Execute themethod
  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"]);
 }
}


10、 如何通過WMI終止一個進程?
using System;
using System.Management;

// This exampledemonstrates how to stop a system service.
class Sample_InvokeMethodOptions
{
    public static int Main(string[] args) {
        ManagementObject service =
            new ManagementObject("win32_service=\"winmgmt\"");
        InvokeMethodOptions options = newInvokeMethodOptions();
        options.Timeout = newTimeSpan(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;

           // 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 SDKbr/>http://msdn.microsoft.com/library/default.asp?url=/library/en- us/wmisdk/wmi/wmi_start_page.asp

WMI使用說明(csdn)br/>http://www.csdn.net/develop/article/15/15346.shtm

WMI技術的應用 for .net(csdn)br/>http://www.csdn.net/develop/article/16/16419.shtm

在.NET中輕鬆獲取系統信息(1) -WMI篇(csdn)br/>http://www.csdn.net/develop/article/15/15744.shtm


 
 

 13、 一些技巧
我使用WMI可以取出網卡的MAC地址,CPU的系列號,主板的系列號,其中主板的系列號已經覈對過沒有錯的,其餘的有待於驗證,因爲我使用的是筆記本,筆記本背面有一個主板的系列號,所以可以肯定主板系列號沒有問題

網卡的MAC地址

SELECT MACAddress FROMWin32_NetworkAdapter WHERE ((MACAddress Is Not NULL) AND (Manufacturer <>'Microsoft'))

結果:08:00:46:63:FFC


CPU的系列號

Select ProcessorId FromWin32_Processor

結果:3FEBF9FF00000F24


主板的系列號

Select SerialNumber FromWin32_BIOS

結果:28362630-3700521
獲取硬盤ID
String HDid;
ManagementClass cimobject = new ManagementClass("Win32_DiskDrive");
ManagementObjectCollection moc = cimobject.GetInstances();
foreach(ManagementObject mo in moc)
{
 HDid = (string)mo.Properties["Model"].value;

 MessageBox.Show(HDid );
}


14、 一個使用WMI後的異常處理的問題
下面是我整理的一段代碼.
 
 ManagementObjectCollection queryCollection1;
  ConnectionOptions co = new ConnectionOptions();
  co.Username = "administrator";
  co.Password = "111";
  try
  {
   System.Management.ManagementScope ms = newSystem.Management.ManagementScope(@"\\csnt3\root\cimv2", co);
   System.Management.ObjectQuery oq = newSystem.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem");
   ManagementObjectSearcher query1 = newManagementObjectSearcher(ms,oq);

  queryCollection1 = query1.Get();
   foreach( ManagementObject mo in queryCollection1 )
   {
    string[] ss={""};
    mo.InvokeMethod("Reboot",ss);
    Console.WriteLine(mo.ToString());
   }
  }
  catch(Exception ee)
  {

  Console.WriteLine("error");

  }


15、Windows 管理規範 (WMI) 是可伸縮的系統管理結構,它採用一個統一的、基於標準的、可擴展的面向對象接口。WMI 爲您提供與系統管理信息和基礎 WMI API 交互的標準方法。WMI 主要由系統管理應用程序開發人員和管理員用來訪問和操作系統管理信息。
WMI 可用於生成組織和管理系統信息的工具,使管理員或系統管理人員能夠更密切地監視系統活動。例如,可以使用 WMI 開發一個應用程序,用於在 Web 服務器崩潰呼叫管理員。
將 WMI 與 .NET 框架一起使用
WMI 提供了大量的規範以便爲許多高端應用程序(例如,Microsoft Exchange、Microsoft SQL Server 和 Microsoft Internet 信息服務 (IIS))實現幾乎任何管理任務。管理員可以執行下列任務:
" 監視應用程序的運行狀況。
" 檢測瓶頸或故障。
" 管理和配置應用程序。
" 查詢應用程序數據(使用對象關係的遍歷和查詢)。
" 執行無縫的本地或遠程管理操作。
WMI 結構由以下三層組成:
" 客戶端
使用 WMI 執行操作(例如,讀取管理詳細信息、配置系統和預訂事件)的軟件組件。
" 對象管理器
提供程序與客戶端之間的中間裝置,它提供一些關鍵服務,如標準事件發佈和預訂、事件篩選、查詢引擎等。
" 提供程序
軟件組件,它們捕獲實數據並將其返回到客戶端應用程序,處理來自客戶端的方法調用並將客戶端鏈接到所管理的基礎結構。
通過定義完善的架構向客戶端和應用程序無縫地提供了數據和事件以及配置系統的能力。在 .NET 框架中,System.Management 命名空間提供了用於遍歷 WMI 架構的公共類。
除 了 .NET 框架,還需要在計算機上安裝 WMI 才能使用該命名空間中的管理功能。如果使用的是Windows Millennium Edition、Windows 2000 或 Windows XP,那麼已經安裝了 WMI。否則,將需要從 MSDN 下載 WMI。
用 System.Management 訪問管理信息
System.Management 命名空間是 .NET 框架中的 WMI 命名空間。此命名空間包括下列支持 WMI 操作的第一級類對象:
" ManagementObject 或 ManagementClass:分別爲單個管理對象或類。
" ManagementObjectSearcher:用於根據指定的查詢或枚舉檢索 ManagementObject 或 ManagementClass 對象的集合。
" ManagementEventWatcher:用於預訂來自 WMI 的事件通知。
" ManagementQuery:用作所有查詢類的基礎。
System.Management 類的使用編碼範例對 .NET 框架環境很適合,並且 WMI 在任何適當的候均使用標準基框架。例如,WMI 廣泛利用 .NET 集合類並使用推薦的編碼模式,如 .NET 異步操作的“委託”模式。因此,使用 .NET 框架的開發人員可以使用他們的當前技能訪問有關計算機或應用程序的管理信息。
請參見
使用 WMI 管理應用程序 | 檢索管理對象的集合 | 查詢管理信息 | 預訂和使用管理事件 | 執行管理對象的方法 | 遠程處理和連接選項 | 使用強類型對象
 
獲取CPU序列號代碼
string cpuInfo = "";//cpu序列號
   ManagementClass cimobject = newManagementClass("Win32_Processor");
   ManagementObjectCollection moc = cimobject.GetInstances();
   foreach(ManagementObject mo in moc)
   {
    cpuInfo =mo.Properties["ProcessorId"].value.ToString();
    Console.WriteLine(cpuInfo);
    Console.ReadLine();
   }
獲取網卡硬件地址
using System.Management;
...
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach(ManagementObject mo in moc)
{
if((bool)mo["IPEnabled"] == true)
Console.WriteLine("MAC address\t{0}",mo["MacAddress"].ToString());
mo.Dispose();
}
}
獲取硬盤ID
String HDid;
ManagementClass cimobject = new ManagementClass("Win32_DiskDrive");
ManagementObjectCollection moc = cimobject.GetInstances();
foreach(ManagementObject mo in moc)
{
 HDid = (string)mo.Properties["Model"].value;
 MessageBox.Show(HDid  );
}


16、在.NET中輕鬆獲取系統信息(1) -WMI篇
Montaque
申明:
    1、個人的一點心得,僅供參考
    2、轉載候,請保留原本。

概述:
 不知道大家有沒有這種體會?有候 爲了獲取系統一點點信息,比如考慮一下操作系統的版本號,或者當前屏幕的分辨率。其實說到底就是讀操作系統某個方面的一個屬性值而已,然後就看到我們的程 序中密密麻麻的Win32 API申明,調用,代碼的可讀性和維護性不言而喻。到了.NET,微軟提供了更爲豐富的類,有很多以前要調用API的方法可以在.NET中輕而易舉的調用 實現。今天簡單介紹一個在.NET中如何通過與WMI(Windows 管理規範)的通訊,從而得到獲取信息的目的。
主要思路:
 舉一個獲取操作系統共享目錄和獲取主板號的例子,介紹如何利用System.Managment下面的類獲取系統相關的信息:

正文:
 WMI(Windows管理規範:Windows Management Instrumentation)是Microsoft基於Web的企業管理(WBEM)的實現,同也是一種基於標準的系統管理接口。WMI最早出現在Microsoft Windows 2000系統上,但它同樣可以安裝在Windows NT 4和Windows 9x計算機上。WMI是一種輕鬆獲取系統信息的強大工具。
 在.NET中,有一個System.Management名空間(系統默認沒有引用,我們可以手動添加引用),通過下面的Class的操作,可以查詢系統軟硬件的信息,先看一個簡單的例子:

Imports System.Management
Dim searcher As New ManagementObjectSearcher("SELECT * FROMWin32_share")
Dim share As ManagementObject
 For Each share In searcher.Get()
      MessageBox.Show(share.GetText(TextFormat.Mof))
 Next share
運行的結果是列出了所有系統當前共享的目錄、以及描述等等。

分析一下上面的代碼,可以看到一下幾點:
1、似乎是在進行數據庫操作,有點像SQL語句。其實就是SQL操作,這種語句被成WQL(WMI Query Language),實際上是標準SQL的一個子集加上了WMI的擴展.
2、WQL是個只讀的查詢語言,我們只能查詢響應的數據,不能用UPDATE,INSERT等更新操作
3、代碼很簡單、通俗易懂
4、我們採用了一種MOF(託管對象格式)的顯示。

例子二:獲取當前主板的信息
 上面的例子是一個軟件方面的信息,下面看一個獲取硬件信息的例子,獲取主板的序列號以及製造商:
Dim searcher As New ManagementObjectSearcher("SELECT * FROMWin32_BaseBoard")
Dim share As ManagementObject
   For Each share In searcher.Get()
      Debug.WriteLine("主板製造商:" &share("Manufacturer"))
      Debug.WriteLine("型號:" &share("Product"))
      Debug.WriteLine("序列號:" &share("SerialNumber"))
   Next share
總結以及補充:
 WMI類也是分層次的,具體可以參考msdn中的WMI;轉向.NET平臺開發的候,最好能多看一些關於.NET新特性的介紹,這樣可以大幅度的提升代碼的開發效率以及運行效率。

 


發佈了45 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章