title: C# get variable from powershell script
body: <p>How can I get the powershell variable $test from a c# application?</p>
  
  <p>I tried it like this: </p>
  
  <pre><code>RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
  Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
  runspace.Open();
  
  RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
  
  Pipeline pipeline = runspace.CreatePipeline();
  //Here's how you add a new script with arguments
  Command myCommand = new Command(scriptFile);
  CommandParameter testParam = new CommandParameter("key", "value");
  CommandParameter testParam2 = new CommandParameter("key", "value");
  CommandParameter testParam3 = new CommandParameter("key", "value");
  myCommand.Parameters.Add(testParam);
  myCommand.Parameters.Add(testParam2);
  myCommand.Parameters.Add(testParam3);
  
  pipeline.Commands.Add(myCommand);
  
  // Execute PowerShell script
  var results = pipeline.Invoke();
  var resultVariable = runspace.SessionStateProxy.PSVariable.GetValue("test");
  </code></pre>
  
  <p><code>resultVariable</code> is <code>null</code>. But I filled it in powershell with an int (i.e. $test = 4).</p>