How to make System.Management.Automation.PowerShell output same as run thru command line

Viewed 2554

Is there any way to get powershell output in c# same way as it is when running command manually via powershell cmd? I.e. for example:

PS C:\temp> gci


    Directory: C:\temp


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        19.10.2018      9:57            SomeDir
-a---        13.11.2018     17:03       3306 Somelog.log

And c# code:

PowerShell ps = PowerShell.Create();
ps.AddCommand("gci");
ICollection<PSObject> results = ps.Invoke();
foreach (PSObject invoke in results)
{
   Console.WriteLine(invoke.ToString());
}

gives me:

SomeDir
Somelog.log
1 Answers

Append a (final) pipeline segment that calls Out-String, which produces the same representation that you would see in the console, as a single, multi-line string:

  using (var ps = PowerShell.Create())
  {
    ps.AddScript("gci | Out-String");
    foreach (PSObject o in ps.Invoke())
    {
      Console.WriteLine(o.ToString());
    }
  }

Out-String uses a default output-line width, which you can override with the -Width parameter.
To receive the output as a collection of lines instead of as a single, multi-line string, use -Stream.

If you want more control over the output formatting, you can precede the Out-String call with another pipeline segment that calls one of the Format-* cmdlets, such as Format-Table.

Caveat:

As boxdog points out, this approach is only suitable for obtaining for-display output, because the resulting string is not meant to be used for programmatic processing (you've lost the original objects' type information, and the specific output format is not guaranteed to have long-term stability).

Of course, you first can store the original output objects in an intermediate step in order to preserve them for later programmatic processing.

Related