【问题标题】:Where "Write-Host" output goes in Powershell System.Management.Automation Reference assemblies 4.0Powershell System.Management.Automation Reference assembly 4.0 中的“Write-Host”输出的位置
【发布时间】:2018-08-30 15:51:54
【问题描述】:

我正在使用 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# pipeline powershell-4.0 runspace


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 2015-05-19
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多