C# 進行WMI操作的內容封裝在System.Management.dll中,具體的在MSDN有詳細描述,預設是用[“**’]去讀取和設定屬性等。
此處介紹一個自動產生強型別的封裝軟體,這樣處理起來就簡單了很多,不用在反覆的查看參數等資訊了。
1、 使用WMIExplorer產生WMI對應的封裝類
2、 針對產生類可以進行強型別操作。
WMIExplorer可以在http://www.primaltools.com/downloads/communitytools/中找到。
如示,選擇需要操作的CIM類別,右鍵產生即可。產生類包括了各種屬性和操作的方法。
以Win32_Process管理機器上的進程為例,針對產生的類的操作方法:
using ROOT.CIMV2.Win32;Process.StaticScope = this.scope;var ps = Process.GetInstances();foreach (var p in ps){using(Process m = p as Process){System.Diagnostics.Debug.WriteLine(m.Name);if (m.Name == "notepad.exe"){m.Terminate(1);}}}uint pid;Process.Create("notepad.exe", null, null, out pid);var my = Process.GetInstances(this.scope, "ProcessId=" + pid.ToString());if (my.Count > 0){var i = my.GetEnumerator();i.MoveNext();Process p = i.Current as Process;p.Terminate(1);}//另一種形式的對比:
ManagementObject mo = new ManagementClass(this.scope, new ManagementPath("MSFT_SIPESUserContactData"), new ObjectGetOptions()).CreateInstance(); mo["UserInstanceID"] = this.userId; mo["SIPURI"] = sip; mo["GroupID"] = groupIds; mo["Name"] = name; mo["Subscribed"] = true; mo.Put(); SIPESUserContactData.StaticScope = this.scope; SIPESUserContactData c = SIPESUserContactData.CreateInstance(); c.LateBoundObject["UserInstanceID"] = this.userId; c.LateBoundObject["SIPURI"] = sip; c.LateBoundObject["GroupID"] = groupIds; c.LateBoundObject["Name"] = name; c.LateBoundObject["Subscribed"] = true; c.CommitObject();
以上可見,由於產生類中包括了屬性名稱字,即使使用名字時,直接參考類就行了。
方便了很多。
這個例子是操作進程和Office Communicator伺服器上的連絡人的操作樣本等。
http://cid-56b433ad3d1871e3.office.live.com/self.aspx/.Public/WMIDemo.zip