1
votes

I have powershell script file, which does something and outputs the result. If I'm manually running it on my remote host using cmd, I'll get the clear output.

But when I'm trying to execute script via PowerShell Runspace using c# I'm not able to see script's output. Only command itself.

using (PowerShell powershell = PowerShell.Create())
{
  try
  {
    PowerShell ps = PowerShell.Create();
    ps.AddScript("c:\temp\myps.ps1");
    ICollection<PSObject> results = ps.Invoke();
    using (StringWriter sw = new StringWriter())
    {
      foreach (PSObject invoke in results)
        sw.WriteLine(invoke.ToString());

      outp = sw.ToString();
    }

    //Script errors
    if (ps.Streams.Error.Count > 0)
    {
      outp += Environment.NewLine + string.Format("{0} errors: ", ps.Streams.Error.Count);
      foreach (ErrorRecord err in ps.Streams.Error)
        outp += Environment.NewLine + err.ToString();
    }
  }
  catch (Exception e)
  {
    // Terminating errors
    outp = "Critical error: " + e.Message;
  }
}

remoteRunspace.Close();

//In the end outp for me = "c:\temp\myps.ps1"

How can I access the output from C#?

2

2 Answers

2
votes

See this documentation about the PowerShell class: https://msdn.microsoft.com/en-us/library/system.management.automation.powershell(v=vs.85).aspx

Looks like you need to access the members of the PSObject to get the output. Otherwise, it will just send laim ToString() data out to the StringBuilder object. Do you have any example of what you're getting back you can show? I may be able to provide a better answer with a sample. Also, where's the remote runspace located?

Thanks!

1
votes

Next code working for me:

try
  {
    PowerShell ps = PowerShell.Create().AddScript("c:\temp\myps.ps1", true);
    ps.Runspace = remoteRunspace;
    ICollection<PSObject> results = ps.Invoke();
    using (StringWriter sw = new StringWriter())
    {
      foreach (PSObject invoke in results)
        sw.WriteLine(invoke.ToString());

      outp = sw.ToString();
    }

    //Script errors
    if (ps.Streams.Error.Count > 0)
    {
      outp += Environment.NewLine + string.Format("{0} errors: ", ps.Streams.Error.Count);
      foreach (ErrorRecord err in ps.Streams.Error)
        outp += Environment.NewLine + err.ToString();
    }
  }
  catch (Exception e)
  {
    // Terminating errors
    outp = "Critical error: " + e.Message;
  }
}

remoteRunspace.Close();