Reputation: 5313
Using C# with System.Management.Automation to run a PowerShell command - I'm trying to understand the purpose/intention of the Pipeline.Output property. This code:
class Program
{
static void Main(string[] args)
{
var results = new List<PSObject>();
var stdout = new List<PSObject>();
using (var runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
using (var pipeline = runspace.CreatePipeline())
{
pipeline.Commands.Add(new Command("Get-ChildItem"));
results.AddRange(pipeline.Invoke());
stdout.AddRange(pipeline.Output.ReadToEnd());
}
runspace.Close();
}
Console.WriteLine("results.Count: {0}", results.Count);
Console.WriteLine("stdout.Count: {0}", stdout.Count);
}
}
Prints:
results.Count: 7
stdout.Count: 0
I would expect both counts to be 7. The documentation is sparse on Pipeline.Output. Can anyone shed some light on what Pipeline.Output is supposed to be used for? What am I misunderstanding?
Upvotes: 1
Views: 981
Reputation: 174445
When you call Invoke()
it returns the output immediately - Output
only gets populated when you invoke the pipeline asynchronously.
Example, invoking and waiting for maximum a second:
pipeline.InvokeAsync();
pipeline.Output.WaitHandle.WaitOne(1000);
if(pipeline.PipelineStateInfo.State == PipelineState.Completed) {
stdout.AddRange(pipeline.Output.ReadToEnd());
}
Or better yet, set up an event handler for the StateChanged event
Upvotes: 2