title: Invoke remote powershell command from C#
body: <p>I'm trying to run an invoke-command cmdlet using C# but I can't figure out the right syntax. I just want to run this simple command:</p>
  
  <pre><code>invoke-command -ComputerName mycomp.mylab.com -ScriptBlock {"get-childitem C:\windows"}
  </code></pre>
  
  <p>In C# code, I have done the following:</p>
  
  <pre><code>InitialSessionState initial = InitialSessionState.CreateDefault();
  Runspace runspace = RunspaceFactory.CreateRunspace(initial);
  runspace.Open();
  PowerShell ps = PowerShell.Create();
  ps.Runspace = runspace;
  ps.AddCommand("invoke-command");
  ps.AddParameter("ComputerName", "mycomp.mylab.com");
  ps.AddParameter("ScriptBlock", "get-childitem C:\\windows");
  foreach (PSObject obj in ps.Invoke())
  {
     // Do Something
  }
  </code></pre>
  
  <p>When I run this, I get an exception:</p>
  
  <pre><code>Cannot bind parameter 'ScriptBlock'. Cannot convert the "get-childitem C:\windows" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
  </code></pre>
  
  <p>I'm guessing I need to use ScriptBlock type here somewhere, but don't know how to. This is just a simple example to get started with, the real use case would involve running a larger script block with multiple commands in it, so any help on how to do this would be highly appreciated.</p>
  
  <p>Thanks</p>