首页 > 解决方案 > Powershell System.Management.Automation Reference assembly 4.0 中的“Write-Host”输出的位置

问题描述

我正在使用 System.Management.Automation 和带有 C# 的参考程序集 4.0 我需要查看 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);
}

标签: c#pipelinepowershell-4.0runspace

解决方案


我在如何在其中包含 Write-Host 命令的代码创建的 powershell shell 中执行脚本?

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

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

推荐阅读