为什么PowerShell Pipeline.Output.ReadToEnd返回一个空集合?

时间:2015-05-18 16:23:43

标签: c# powershell

使用C#和System.Management.Automation运行PowerShell命令 - 我试图了解Pipeline.Output属性的目的/意图。这段代码:

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);
    }
}

打印:

results.Count: 7
stdout.Count: 0

我希望两个计数都是7.文档在Pipeline.Output上很少。任何人都可以了解Pipeline.Output应该用于什么?我误解了什么?

1 个答案:

答案 0 :(得分:2)

当您调用Invoke()时,它会立即返回输出 - Output仅在您异步调用管道时填充。

示例,调用并等待最多秒:

pipeline.InvokeAsync();
pipeline.Output.WaitHandle.WaitOne(1000);
if(pipeline.PipelineStateInfo.State == PipelineState.Completed) {
    stdout.AddRange(pipeline.Output.ReadToEnd());
}

或者更好的是,为StateChanged event

设置事件处理程序