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#?