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

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

 
   using System;
   using System.Management.Automation;
 
   namespace PowerShellApplication
   {
      class Program
      {
         \\ The Execution Account needs to have the access right to query on SCCM.
         static void Main(string[] args)
         {
            RunPowerShellScript("1234");
         }
 
         private static void RunPowerShellScript(string computerid)
         {
            PowerShell ps = PowerShell.Create();
 
            ps.AddScript("$SiteName=\"<SCCM Site Name>\";");
            ps.AddScript("$SCCMServer=\"<SCCM Server Name\";");
            ps.AddScript("$SCCMNS=\"root\\sms\\site_$SiteName\";");
            ps.AddScript("$query = \"select * from SMS_G_System_ADD_REMOVE_PROGRAMS where ResourceID = " + computerid + " \";");
            ps.AddScript("Get-WmiObject -namespace $SCCMNS -computer $SCCMServer -query $query | Select-Object DisplayName, version;");
 
            List<Software> list = new List<Software>();
 
            string DisplayName = "";
            string version = "";
 
            foreach (PSObject result in ps.Invoke())
            {
               if (result.Members["DisplayName"] != null && result.Members["DisplayName"].Value != null)
                  DisplayName = result.Members["DisplayName"].Value.ToString();
               else
                  DisplayName = "";
 
               if (result.Members["version"] != null && result.Members["version"].Value != null)
                  version = result.Members["version"].Value.ToString();
               else
                  version = "";
 
               Console.WriteLine(DisplayName + " : " + version);
               list.Add(new Software(DisplayName, version));
            }
 
            Console.WriteLine(list.Count);
 
            Console.ReadLine();
         }
 
         class Software
         {
            string DisplayName;
            string version;
 
            public Software(string DisplayName, string version)
            {
               this.DisplayName = DisplayName;
               this.version = version;
            }
         }
      }
   }