title: Run PowerShell-Script from C# Application
body: <p>I'm trying to execute a PowerShell script from a c# application. The script has to be executed under a special usercontext.</p>
  
  <p>I've tried different scenarios some are working some not:</p>
  
  <p><strong>1. direct call from PowerShell</strong></p>
  
  <p>I've called the script directly from a ps-console which is running under the correct usercredentials.</p>
  
  <pre><code>C:\Scripts\GroupNewGroup.ps1 1
  </code></pre>
  
  <p><strong>Result:</strong> Successfully running the script.</p>
  
  <p><strong>2. from a c# console application</strong></p>
  
  <p>I've called the script from a c# consoleapplication which is started under the correct usercredentials.</p>
  
  <p>Code: </p>
  
  <pre><code> string cmdArg = "C:\\Scripts\\GroupNewGroup.ps1 1"
   Runspace runspace = RunspaceFactory.CreateRunspace();
   runspace.ApartmentState = System.Threading.ApartmentState.STA;
   runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
  
  
       runspace.Open();
  
   Pipeline pipeline = runspace.CreatePipeline();
  
   pipeline.Commands.AddScript(cmdArg);
   pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
   Collection&lt;PSObject&gt; results = pipeline.Invoke();
   var error = pipeline.Error.ReadToEnd();
   runspace.Close();
  
   if (error.Count &gt;= 1)
   {
       string errors = "";
       foreach (var Error in error)
       {
           errors = errors + " " + Error.ToString();
       }
   }
  </code></pre>
  
  <p><strong>Result:</strong> No Success. And a lot of "Null-Array" exceptions.</p>
  
  <p><strong>3. from a c# console application - code side impersonating</strong> </p>
  
  <p>(<a href="http://platinumdogs.me/2008/10/30/net-c-impersonation-with-network-credentials" rel="noreferrer">http://platinumdogs.me/2008/10/30/net-c-impersonation-with-network-credentials</a>)</p>
  
  <p>I've called the script from a c# consoleapplication which is started under the correct usercredentials and the code contains impersonation.</p>
  
  <p>Code:</p>
  
  <pre><code>using (new Impersonator("Administrator2", "domain", "testPW"))
  
                     {
    using (RunspaceInvoke invoker = new RunspaceInvoke()) 
  { 
      invoker.Invoke("Set-ExecutionPolicy Unrestricted"); 
  } 
  
       string cmdArg = "C:\\Scripts\\GroupNewGroup.ps1 1";
       Runspace runspace = RunspaceFactory.CreateRunspace();
       runspace.ApartmentState = System.Threading.ApartmentState.STA;
       runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
  
  
           runspace.Open();
  
       Pipeline pipeline = runspace.CreatePipeline();
  
       pipeline.Commands.AddScript(cmdArg);
       pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
       Collection&lt;PSObject&gt; results = pipeline.Invoke();
       var error = pipeline.Error.ReadToEnd();
       runspace.Close();
  
       if (error.Count &gt;= 1)
       {
           string errors = "";
           foreach (var Error in error)
           {
               errors = errors + " " + Error.ToString();
           }
       }
   }  
  </code></pre>
  
  <p><strong>Results:</strong></p>
  
  <ul>
  <li>The term 'Get-Contact' 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.</li>
  <li>The term 'C:\Scripts\FunctionsObjects.ps1' 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.</li>
  <li>No snap-ins have been registered for Windows PowerShell version 2.
  Microsoft.Office.Server, Version=14.0.0.0, Culture=neutral,
  PublicKeyToken=71e9bce111e9429c</li>
  <li>System.DirectoryServices.AccountManagement, Version=4.0.0.0,
  Culture=neutral, PublicKeyToken=b77a5c561934e089</li>
  <li>Exception calling ".ctor" with "1" argument(s): "The Web application
  at <code>http://XXXX/websites/Test4/</code> could not be found. Verify that you
  have typed the URL correctly. If the URL should be serving existing
  content, the system administrator may need to add a new request URL
  mapping to the intended application."</li>
  <li>You cannot call a method on a null-valued expression. Cannot index
  into a null array.</li>
  </ul>
  
  <p><strong>Until now there is no working answer</strong></p>
  
  <p>Does anyone know why there are differences and how to solve the problem?</p>