【问题标题】:Is it possible to utilize Format-Table from C#?是否可以使用 C# 中的 Format-Table?
【发布时间】:2014-06-01 19:36:33
【问题描述】:

我想要一个使用Format-Table 来显示对象的C# 控制台程序。这是一个简单的 C# 程序:

using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;

namespace PowerShellFormatTableTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var ps = PowerShell.Create()
                .AddCommand("Get-Process")
                .AddCommand("Format-Table");

            foreach (var result in ps.Invoke())
            {
                // ...
            }
        }
    }
}

大部分result 元素当然是FormatEntryData 对象。

有没有办法将Format-Table 格式的输出打印到控制台?

上面的例子只是一个简单的例子。通常,我会传递任意对象

【问题讨论】:

    标签: c# .net powershell cmdlets


    【解决方案1】:

    如果您将结果从Format-Table 传送到Out-String,那么您应该得到与字符串对象相同的输出。试试这个:

    var ps = PowerShell.Create()
        .AddCommand("Get-Process")
        .AddCommand("Format-Table")
        .AddCommand("Out-String");
    

    【讨论】:

      【解决方案2】:

      以下是更新的示例以展示 Frode 的建议:

      using System;
      using System.Collections.Generic;
      using System.Text;
      using System.Management.Automation;
      
      namespace PowerShellFormatTableTest
      {
          class Program
          {
              static void Main(string[] args)
              {
                  var ps = PowerShell.Create()
                      .AddCommand("Get-Process")
                      .AddCommand("Format-Table")
                      .AddCommand("Out-String");
      
                  Console.WriteLine(ps.Invoke()[0]);
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-28
        • 1970-01-01
        • 2019-01-18
        • 2021-08-26
        • 1970-01-01
        • 2023-04-10
        相关资源
        最近更新 更多