在Powershell System.Management.Automation参考程序集4.0中,“Write-Host”输出的去向是什么?

5
我正在使用带有C#的4.0参考程序集的System.Management.Automation。我需要查看Write-Host的输出。文档中写道,Write-Host将被输出到输出流中。在使用powershell 4.0的参考程序集时,如何获取C#中的Write-Host输出流?
我知道,在Powershell版本5.0中后来添加了信息管道,并且Write-Host和Write-Information始终将输出传输到信息管道中。
但是在使用powershell 4.0 的参考程序集时,我需要查看Write-Host的输出。使用下面的代码,我无法在任何地方看到Write-Host的输出。即使是在输出和输出集合中也看不到。
目前,我已经订阅了以下流。
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);
}
2个回答

4
我在这个链接中找到了一个有效地回答同样问题的方法。
在你的AddScript调用之前,添加以下两个语句:
powerShell.AddScript("function Write-Host($out) {Write-Output $out}").Invoke();
powerShell.Commands.Clear();

0

如果您想继续使用Pipeline类,可以使用Command.MergeMyResultsmethod。例如,将所有类型的流重定向到管道输出:

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());
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接