Powershell System.Management.Automation参考程序集4.0中“写入主机”输出的位置

时间:2018-08-30 15:51:55

标签: c# pipeline powershell-v4.0 runspace

我正在使用带有C#的参考程序集4.0的System.Management.Automation 我需要查看Write-Host的输出。文档说Write-Host将在输出流中输出。使用powershell 4.0的参考程序集时,用C#获取Write-Host输出的输出流是什么。

我知道稍后在Powershell 5.0版中添加了信息管道,并且Write-Host和Write-Information始终将输出管道传输到Information Pipeline。

但是,我需要在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);
}

1 个答案:

答案 0 :(得分:1)

我在How can I execute scripts in a code created powershell shell that has Write-Host commands in it?

找到了一个有效回答该问题的答案

在调用AddScript之前,请添加以下两个语句:

powerShell.AddScript("function Write-Host($out) {Write-Output $out}").Invoke();
powerShell.Commands.Clear();