3

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
  • 38,279
  • 56
  • 171
  • 280
Usman
  • 2,602
  • 4
  • 38
  • 74

1 Answers1

2

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
  • 739
  • 6
  • 20