Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Command in C#

Tags:

c#

powershell

wmi

I am trying to query the names all of the WMI classes within the root\CIMV2 namespace. Is there a way to use a powershell command to retrieve this information in C# ?

like image 376
Sanch01R Avatar asked Dec 19 '09 15:12

Sanch01R


2 Answers

Personally I would go with Helen's approach and eliminate taking a dependency on PowerShell. That said, here's how you would code this in C# to use PowerShell to retrieve the desired info:

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);
                }
            }
        }
    }
}
like image 185
Keith Hill Avatar answered Oct 17 '22 09:10

Keith Hill


Along the lines of Keith's approach

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);
            }
        }
    }
}
like image 43
Doug Finke Avatar answered Oct 17 '22 08:10

Doug Finke