title: Running PowerShell cmdlets in C#
body: <p>I need to run powershell cmdlets using C# in Visual Studio Console.</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  using System.Management.Automation;
  using System.Threading;
  using System.Management.Automation.Runspaces;
  using System.Collections.ObjectModel;
  using System.Collections;
  
  namespace ConsoleApp1
  {
      class Program
      {
          private static string RunScript()
          {
  
              Runspace runSpace = RunspaceFactory.CreateRunspace();
              runSpace.Open();
              Pipeline pipeline = runSpace.CreatePipeline();
              Command cmd = new Command("Connect-MsolService"); 
              pipeline.Commands.Add(cmd);
              ICollection results = pipeline.Invoke();  // Here exception occurs
              runSpace.Close();
              StringBuilder stringBuilder = new StringBuilder();
              foreach (PSObject obj in results)
              {
                  stringBuilder.AppendLine(obj.ToString());
              }
  
              return stringBuilder.ToString();
          }
  
  
  
  
          static void Main(string[] args)
          {
              using (PowerShell PowerShellInstance = PowerShell.Create())
              {
                  Console.WriteLine(RunScript());
                  Console.ReadKey();
              }
          }
      }
  }
  </code></pre>
  
  <p>When I run the code an Exception occurs:</p>
  
  <blockquote>
    <p>The term 'Connect-MsolService' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.</p>
  </blockquote>
  
  <p>Even though it works when I run the commands in Powershell.</p>