0

I have following code which I call from my C#.net service which results in calling the powershell script twice.

using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
      runspace.Open();

      runspace.SessionStateProxy.SetVariable("scriptpath", scriptPath);
      runspace.SessionStateProxy.SetVariable("DBRecordKey", reportId.Key);
      runspace.SessionStateProxy.SetVariable("SymbolPath", symbolPath);
      Logger.Log("DBRecordKey = " + reportId.Key, writer);
      using (Pipeline pipeline = runspace.CreatePipeline(scriptText))
      {
             //Here's how you add a new script with arguments
             pipeline.Commands.AddScript(scriptText);

             // Execute PowerShell script
             Collection<PSObject> results = pipeline.Invoke();

             StringBuilder outputString = new StringBuilder();
             foreach (PSObject obj in results)
             {
                     outputString.AppendLine(obj.ToString());
             }
             Logger.Log("outputString 2 - " + outputString, writer);
             pipeline.Stop();
             runspace.Close();
      }
}

Is there anything wrong with my code?

1 Answer 1

1

You're specifying the script both in CreatePipeline(scriptText) and AddScript(scriptText). I'm not a Powershell user, but I'd suggest that either you want

using (Pipeline pipeline = runspace.CreatePipeline())
{
    pipeline.Commands.AddScript(scriptText);
    ...
}

... or you want to remove the AddScript call entirely. If there's a particular reason you need AddScript, then creating the pipeline without the scriptText seems the logical approach.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.