Powershell/C#: Invoking a pipeline asynchronously & displaying the results

牧云@^-^@ 提交于 2019-11-29 17:55:43

Got it ! Here is the full code...

Add a Rich Textbox = txtOutput on a Form first & Add a reference to

C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll

    IAsyncResult _invokeResult; 

    PowerShell _ps = PowerShell.Create();

    delegate void SetOutput(string value);

    // Monitor the DataAdded
    _ps.Streams.Verbose.DataAdded += new EventHandler<DataAddedEventArgs>(Verbose_DataAdded);

    var sr = new StreamReader(@"C:\MyScript.ps1");
    _ps.AddScript(sr.ReadToEnd());
    _invokeResult = _ps.BeginInvoke<PSObject>(null, null, AsyncInvoke, null);


   void Verbose_DataAdded(object sender, DataAddedEventArgs e)
   {
       System.Diagnostics.Debug.Print( ((PSDataCollection<VerboseRecord>) sender)[e.Index].ToString()) ;

       if (txtOutput.InvokeRequired)
       {
           string msg = ((PSDataCollection<VerboseRecord>) sender)[e.Index].ToString();
           txtOutput.Invoke(new SetOutput(Execute), new object[] { msg} );
       }
   }



   void AsyncInvoke(IAsyncResult ar)
   {
       // end
       try
       {
           _ps.EndInvoke(ar);
       }
       catch (Exception ex)
       {
             // do something with the error...
       }
  }

private void Execute(string msg)
        {
            txtOutput.SelectionFont = new Font(txtOutput.SelectionFont.FontFamily, 9.0f);
            txtOutput.AppendText(msg);
            txtOutput.ScrollToCaret();
        }

If you only want to output Write-Verbose output to the GUI then it would be easier to monitor the Streams.Verbose collection after the InvokeAsync. If you want to scan all the output then use the PipelineReader. Subscribe to its DataReady event and in that event handler do a NonBlockingRead to get the data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!