C# – Execute PowerShell Command in Code & Iterate returned result to Code Variable

C# – Execute PowerShell Command in Code & Iterate returned result to Code Variable

 
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Text;
   using System.Management.Automation;
 
   namespace PowerShellConsole
   {
      class Program
      {
         static void Main(string[] args)
         {
            List<Process> list = RunPowerShellScript();
            Console.ReadLine();
         }
 
         private static void RunPowerShellScript()
         {
            PowerShell ps = PowerShell.Create();
 
            ps.AddCommand("Get-Process");
 
            List<Process> list = new List<Process>();
 
            foreach (PSObject result in ps.Invoke())
            {
               Console.WriteLine(result.Members["ProcessName"].Value + " : " + result.Members["Id"].Value);
               list.Add(new Process(Int32.Parse(result.Members["Id"].Value.ToString()), result.Members["ProcessName"].Value.ToString()));
            }
         }
 
         class Process
         {
            int Id { get; set; }
            string ProcessName { get; set; }
 
            public Process(int Id, string ProcessName)
            {
               this.ProcessName = ProcessName;
               this.Id = Id;
            }
         }
      }
   }