title: To call a powershell script file (example.ps1) from C#
body: <p>I tried running a script localwindows.ps1 from C# using the following Code :</p>
  <pre><code>PSCredential credential = new PSCredential(userName, securePassword);
  WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, &quot;machineName&quot;, 5985, &quot;/wsman&quot;, shellUri, credential);
  using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
  {
      runspace.Open();
      String file = &quot;C:\\localwindows.ps1&quot;;
      Pipeline pipeline = runspace.CreatePipeline();
      pipeline.Commands.AddScript(file);
      pipeline.Commands.Add(&quot;Out-String&quot;);
      Collection&lt;PSObject&gt; results = pipeline.Invoke();
  }
  
                    
  </code></pre>
  <p>But getting exception :'The term 'C:\localwindows.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program.</p>
  <p>So I tried the following :</p>
  <pre><code>PSCredential credential = new PSCredential(userName, securePassword);
  WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, &quot;machineName&quot;, 5985, &quot;/wsman&quot;, shellUri, credential);
  using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
  {
  
      runspace.Open();
   
      using (PowerShell powershell = PowerShell.Create())
      {
          powershell.Runspace = runspace;           
          
          PSCommand new1 = new PSCommand();
          String machinename = &quot;machinename&quot;;
          String file = &quot;C:\\localwindows.ps1&quot;;
          new1.AddCommand(&quot;Invoke-Command&quot;);
          new1.AddParameter(&quot;computername&quot;, machinename);
          new1.AddParameter(&quot;filepath&quot;, file);         
          
  
          powershell.Commands = new1;
          Console.WriteLine(powershell.Commands.ToString());
          Collection&lt;PSObject&gt; results = powershell.Invoke();
         
       }
  </code></pre>
  <p>I am getting the error : &quot;Cannot find path 'C:\localwindows.ps1' because it does not exist.&quot;</p>
  <p>But using command  'Invoke-Command -ComputerName &quot;machineName&quot; -filepath C:\localwindows.ps1' ,from powershell in local machine created a new account in the remote machine.</p>
  <p>How to call the script localwindows.ps1 from C#?
  How to execute the command 'Invoke-Command -ComputerName &quot;machineName&quot; -filepath C:\localwindows.ps1' through C#?</p>
  <p>The script localwindows.ps1 is</p>
  <pre><code>$comp = [adsi]“WinNT://machinename,computer”
  $user = $comp.Create(“User”, &quot;account3&quot;)
  $user.SetPassword(“change,password.10&quot;)
  $user.SetInfo()
  </code></pre>