5

I am using System.Management.Automation with reference assemblies 4.0 with C#

I need to see the output of Write-Host. Documentation says that Write-Host will be outputted in the output stream. What is the output stream for getting Write-Host output in C# while using reference assemblies of powershell 4.0.

I know Information pipeline was being later added in Powershell version 5.0 and Write-Host and Write-Information always pipe the output to Information Pipeline.

But I need to see the output of Write-Host while with reference assemblies for powershell 4.0. With the following code, I am not able to see the output of Write-Host anywhere. Nor at output and not in the output collections.

Currently I have subscribed to following streams.

using (var powerShell = PowerShell.Create(iss))
{           
    var psScript = "Write-Host test input";
    powerShell.AddScript(psScript);

    powerShell.Streams.Debug.DataAdding += OnDebugDataAdding; 
    powerShell.Streams.Error.DataAdding += OnErrorAdding;
    powerShell.Streams.Warning.DataAdding += OnWarningAdding;
    powerShell.Streams.Verbose.DataAdding += OnVerboseAdding;

    var outputCollection = new PSDataCollection<PSObject>();
    outputCollection.DataAdding += OnOutputDataAdding; // all spitted outputs getting into outputCollection

    powerShell.Invoke(null, outputCollection);
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Usman
  • 2,742
  • 4
  • 44
  • 82

2 Answers2

4

I found an answer to effectively this same question at How can I execute scripts in a code created powershell shell that has Write-Host commands in it?

Before your AddScript call, add these two statements:

powerShell.AddScript("function Write-Host($out) {Write-Output $out}").Invoke();
powerShell.Commands.Clear();
Tim Sparkles
  • 771
  • 6
  • 21
0

If you want to keep using the Pipeline class, you can use the Command.MergeMyResults method. For example, to redirect all type of streams to pipeline output:

private string RunScript(string scriptText) {

    Runspace runspace = RunspaceFactory.CreateRunspace();

    runspace.Open();

    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript("Write-Host Test");
    pipeline.Commands[pipeline.Commands.Count-1]
       .MergeMyResults(PipelineResultTypes.All, PipelineResultTypes.Output)
    
    Collection < PSObject > results = pipeline.Invoke();

    runspace.Close();

    foreach(PSObject obj in results) {
        Console.WriteLine(obj.ToString());
    }
}
CravateRouge
  • 130
  • 7