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

前端 未结 2 958
孤独总比滥情好
孤独总比滥情好 2020-12-20 09:59

As per this sample - http://msdn.microsoft.com/en-us/library/windows/desktop/ee706590(v=vs.85).aspx,

I am trying to invoke my script in an async way. But, at the sa

相关标签:
2条回答
  • 2020-12-20 10:41

    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();
            }
    
    0 讨论(0)
  • 2020-12-20 10:41

    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.

    0 讨论(0)
提交回复
热议问题