Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture a Powershell CmdLet's Object output when the CmdLet is programmatically Invoked from C#

Background

  • PowerShell 3 with SDK
  • C# with Framework 4.5

Implementation

I have implemented my own PSHost alogn with PSHostUserInterface. In PSHostUserInterface I override all Write... methods and colleting the to one variable which serves the output.

Problem

In my application I calling Cmdlets which use WriteObject as their output. In the PSHostUserInterface.Write... methods I am getting everything but these WriteObject's output. For example, I see this in regular PowerShell:

This is sample string output from the command

Here we have object from Cmdlet.WriteObject function

This is another string output from the command

This is what I get in my custom PSHost in my application:

This is sample string output from the command

This is another string output from the command

Question

How can I get in C# all the outputs of the Cmdlet?

Many thanks

like image 451
krs Avatar asked Nov 11 '22 20:11

krs


1 Answers

I think Richard is onto it with his comment. If you are calling the cmdlets by using Pipeline.Invoke(), you have to either:

  • A) Call Pipeline.Invoke again with those objects and pipe them into Out-Default or
  • B) Just append the command Out-Default to the original pipeline. This will tell PowerShell to send the output to the display (and use the default formatting).

Normally, when you stash the resulting objects that are output by a pipeline, either in a PowerShell variable $res = Get-Process or in C# as output from Invoke(), you are dealing with the actual .NET objects. The formatting & rendering of those objects to the host is another step that PowerShell will do for you if the pipeline output is not captured. PowerShell effectively appends a | Out-Default to the pipeline in this case.

like image 129
Keith Hill Avatar answered Nov 14 '22 21:11

Keith Hill