Question

I'd like to have a C# console program which uses Format-Table to display objects. Here's a simple C# program:

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())
            {
                // ...
            }
        }
    }
}

The majority of the result elements are of course FormatEntryData objects.

Is there a way to print the Format-Table formatted output to the console?

The above example is just a trivial example. Normally, I'll be passing arbitrary objects

Was it helpful?

Solution

If you pipe the result from Format-Table to Out-String, then you should get the same output as a string-object. Try this:

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

OTHER TIPS

Here's the example updated to demonstrate Frode's suggestion:

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]);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top