2009-12-19 18 views
7

Sto provando a interrogare i nomi di tutte le classi WMI all'interno dello spazio dei nomi root \ CIMV2. C'è un modo per usare un comando di PowerShell per recuperare queste informazioni in C#?Comando PowerShell in C#

risposta

5

Lungo le linee di approccio di Keith

using System; 
using System.Management.Automation; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var script = @" 
       Get-WmiObject -list -namespace root\cimv2 | Foreach {$_.Name} 
      "; 

      var powerShell = PowerShell.Create(); 
      powerShell.AddScript(script); 

      foreach (var className in powerShell.Invoke()) 
      { 
       Console.WriteLine(className); 
      } 
     } 
    } 
} 
7

Non sono sicuro del motivo per cui hai citato PowerShell; puoi farlo in puro C# e WMI (lo spazio dei nomi System.Management, ovvero).

per ottenere un elenco di tutte le classi WMI, utilizzare la SELECT * FROM Meta_Class query:

using System.Management; 
... 

try 
{ 
    EnumerationOptions options = new EnumerationOptions(); 
    options.ReturnImmediately = true; 
    options.Rewindable = false; 

    ManagementObjectSearcher searcher = 
     new ManagementObjectSearcher("root\\cimv2", "SELECT * FROM Meta_Class", options); 

    ManagementObjectCollection classes = searcher.Get(); 

    foreach (ManagementClass cls in classes) 
    { 
     Console.WriteLine(cls.ClassPath.ClassName); 
    } 
} 
catch (ManagementException exception) 
{ 
    Console.WriteLine(exception.Message); 
} 
3

Personalmente vorrei andare con l'approccio di Helen ed eliminare l'assunzione di dipendenza da PowerShell. Detto questo, ecco come si potrebbe codificare questo in C# per utilizzare PowerShell per recuperare informazioni desiderato:

using System; 
using System.Collections.Generic; 
using System.Collections.ObjectModel; 
using System.Linq; 
using System.Management.Automation; 

namespace RunspaceInvokeExp 
{ 
    class Program 
    { 
     static void Main() 
     { 
      using (var invoker = new RunspaceInvoke()) 
      { 
       string command = @"Get-WmiObject -list -namespace root\cimv2" + 
            " | Foreach {$_.Name}"; 
       Collection<PSObject> results = invoker.Invoke(command); 
       var classNames = results.Select(ps => (string)ps.BaseObject); 
       foreach (var name in classNames) 
       { 
        Console.WriteLine(name); 
       } 
      } 
     } 
    } 
} 
4

Basta notare che v'è uno strumento disponibile che consente di creare, eseguire e salvare gli script WMI scritti in PowerShell, lo strumento PowerShell Scriptomatic, disponibile per il download dal sito Microsoft TechNet.

Utilizzando questo strumento, è possibile esplorare tutte le classi WMI nel root \ CIMV2 o in qualsiasi altro spazio dei nomi WMI.

|Image of PowerShell Scriptomatic tool

+0

Questo funziona perfettamente. Grazie per l'aiuto. – Sanch01R