2011-05-03 61 views
1

我想檢查某個特定的功能是否安裝在某臺機器上。 我有一個PowerShell代碼來檢查這個,現在我想從.net代碼中檢查這個。 我可以看到,在該cmdlet中,代碼檢查是否存在invalid namespace錯誤。檢查是否存在來自C#的WMI名稱空間

當在網上搜索,我發現下面的代碼:

ManagementClass myClass = new ManagementClass(scope, path, getOptions); 

try 
{ 
    myClass.get(); 
} 
catch (System.Management.Exception ex) 
{ 
    if (ex.ErrorCode == ManagementStatus.InvalidNamespace) 
    { 
     return true; 
    } 
} 
... 

我要清理這個代碼位,所以基本上我有2個問題:

  1. 有另一種方式來檢查InvalidNamespace錯誤? (我複製的代碼後來用於調用myClass中的某些方法,所以我想知道能否以某種方式以更直接的方式實現我的目標)

  2. 我真的需要參數getOptions嗎?

回答

4

要獲取所有WMI命名空間,你必須先連接到根命名空間,然後查詢所有__NAMESPACE實例,每個實例遞歸重複此過程。在這種情況下,關於getOptions參數是一個ObjectGetOptions類是不必要的,所以可以爲null。

檢查這個代碼把所有的WMI命名空間(可以填充列表與信息,然後檢查是否命名空間中的機器上存在)

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Management; 

namespace MyConsoleApplication 
{ 
    class Program 
    { 
     static private void GetWmiNameSpaces(string root) 
     { 
      try 
      { 
       ManagementClass nsClass = new ManagementClass(new ManagementScope(root), new ManagementPath("__namespace"), null); 
       foreach (ManagementObject ns in nsClass.GetInstances()) 
       { 
        string namespaceName = root + "\\" + ns["Name"].ToString(); 
        Console.WriteLine(namespaceName); 
        //call the funcion recursively        
        GetWmiNameSpaces(namespaceName); 
       } 
      } 
      catch (ManagementException e) 
      { 
       Console.WriteLine(e.Message); 
      } 
     } 


     static void Main(string[] args) 
     { 
      //set the initial root to search 
      GetWmiNameSpaces("root"); 
      Console.ReadKey(); 
     } 
    } 
} 
相關問題