使用复杂命令渲染Powershell输出

时间:2019-03-01 21:23:50

标签: c# powershell pshost

我试图通过C#应用程序执行PS1文件,并根据严重性捕获/细分输出。错误,调试,信息等。这是Windows窗体应用程序。这是“运行方法”,单击按钮即可调用该方法:

PowerShell m_PSInst = PowerShell.Create();

//Add the script to execute
m_PSInst.AddScript(fileName);

//Attach to the Info Stream
m_PSInst.Streams.Information.DataAdded += (sender, args) =>
{
      var psData = (PSDataCollection<InformationRecord>)sender;

      var results = psData.ReadAll();

      foreach (var result in results)
      {
          AddInfo(result.ToString());
      }
};

//Run Async
Task.Factory.FromAsync(m_PSInst.BeginInvoke(), pResult => m_PSInst.EndInvoke(pResult));

在我的AddInfo方法中,我正在检查对UI层的线程访问

public void AddInfo(string value)
{
    if (InvokeRequired)
    {
        Invoke(new Action<string>(AddInfo), value);
        return;
    }

    infoTextbox.AppendText(value, Color.White);
    allOutputTextbox.AppendText(value, Color.White);

    Application.DoEvents();
}

我的PS1文件的内容如下:

Write-Information "Test-Before"
Get-WebBinding
Write-Information "Test-After"

我看到的是“之前测试”,仅此而已。在Get-WebBinding命令之后,所有输出流似乎什么都没收到。我试过添加一个默认值,输出字符串,甚至定向到输出文件。似乎没有任何作用。

此处未显示的是用于其他流的其他DataAdded方法,包括错误,调试,详细,进度和警告。很乐意停止对此踢自己。 :)

1 个答案:

答案 0 :(得分:1)

我认为这是32/64位的事情。某些Cmdlet仅在64位模式下运行,包括Get-WebBinding Cmdlet。

请尝试确保将pshost编译为64位。