Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell via C# Console Output different

Tags:

c#

powershell

Fairly new to C#, not so new to PowerShell.

I want to use C# to execute PowerShell code. However the output of objects isn't in the same as running commands in a PowerShell window. I get back the object's name rather than its data. Here's what I'm trying:

string script = @"
    get-process | ft
";

PowerShell powerShell = PowerShell.Create();

powerShell.AddScript(script);
var results = powerShell.Invoke();
foreach (var item in results)
{
    Console.WriteLine(item);
}

Returns:

Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData

However in a PowerShell command line window it returns a more formated table view:

PS C:\Dropbox\PowerShell> ps | ft

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id SI ProcessName ------- ------ ----- ----- ----- ------ -- -- ----------- 131 12 1980 2572 85 0.45 13216 1 acrotray

Really would like two things:

  1. code that will produce the same output as the PowerShell command window
  2. an explanation of what is going on so I can learn how to navigate it better

Thanks in advance!

like image 612
Eric Weintraub Avatar asked Oct 19 '22 20:10

Eric Weintraub


1 Answers

I figured it out, thanks to a code example on codeproject I figured out that the command "out-string" needs to be added to the end of all commands. So the extra code to add is:

ps.AddCommand("Out-String");

I wonder if the console is simply doing this or if there is more to it.

like image 92
Eric Weintraub Avatar answered Oct 21 '22 16:10

Eric Weintraub