Comando Powershell in C#

Comando Powershell in C#

Sulla falsariga dell'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);
            }
        }
    }
}

Non sono sicuro del motivo per cui hai menzionato PowerShell; puoi farlo in puro C# e WMI (il System.Management spazio dei nomi, cioè).

Per ottenere un elenco di tutte le classi WMI, utilizzare il SELECT * FROM Meta_Class domanda:

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);
}

Solo per notare che è disponibile uno strumento che consente di creare, eseguire e salvare 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 all'interno di root\CIMV2 o qualsiasi altro spazio dei nomi WMI.