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);
}
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();
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());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.