Reputation: 13
This is a sample code to test a functionality, it has no use in itself. I want to fire the completed event of the PSDataCollection object. I found in Microsoft that the CloseAll method in C++ should be called to let BeginInvoke know that there are no commands left, I'm not sure that this concept applies in C#, I cannot find this method anywhere. The code works because I used the Completed state from InvocationStateChanged. I do not understand why this one is fired and not the other. I searched for days for an answer but there's not much to find.
Thanks
Jean
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace PSAsync
{
public partial class Form1 : Form
{
RunspacePool RSPool;
StringBuilder stringBuilder;
PowerShell Ping1;
IAsyncResult Ping1AsyncResult;
PSDataCollection<PSObject> Output;
public Form1()
{
InitializeComponent();
RSPool = RunspaceFactory.CreateRunspacePool(1, 4);
RSPool.Open();
stringBuilder = new StringBuilder();
}
private void btnPing1_Click(object sender, EventArgs e)
{
Ping1 = PowerShell.Create();
//Instead we rely on the InvocationStateChanged event
lblPing1.Text = "Status:" + Ping1.InvocationStateInfo.State.ToString();
Ping1.InvocationStateChanged += Ping1_InvocationStateChanged;
Ping1.RunspacePool = RSPool;
Ping1.AddCommand("ping").AddArgument("192.168.1.1");
Output = new PSDataCollection<PSObject>();
Output.Completed += Test_Completed;//never gets fired
Output.DataAdded += Output_DataAdded;
Ping1.Streams.Error.DataAdded += Error_DataAdded;
Ping1AsyncResult = Ping1.BeginInvoke<PSObject, PSObject>(null,Output);
}
private void Error_DataAdded(object sender, DataAddedEventArgs e)
{
throw new NotImplementedException();
}
private void Output_DataAdded(object sender, DataAddedEventArgs e)
{
PSDataCollection<PSObject> myp = (PSDataCollection<PSObject>)sender;
Collection<PSObject> results = myp.ReadAll();
foreach (PSObject result in results)
{
this.Invoke((MethodInvoker)delegate
{
// Show the current time in the form's title bar.
this.txtOutput.Text = txtOutput.Text + result.ToString()+Environment.NewLine;
});
}
}
private void Test_Completed(object sender, EventArgs e)
{
throw new NotImplementedException();
}
private void Ping1_InvocationStateChanged(object sender, PSInvocationStateChangedEventArgs e)
{
Console.WriteLine("Invocation State Changed:"+e.InvocationStateInfo.State.ToString());
this.Invoke((MethodInvoker)delegate
{
this.lblPing1.Text = "Status:"+e.InvocationStateInfo.State.ToString();
});
if (e.InvocationStateInfo.State == PSInvocationState.Completed)
{
this.Invoke((MethodInvoker)delegate
{
this.txtOutput.Text = txtOutput.Text +"Status:" + e.InvocationStateInfo.State.ToString();
});
}
}
private void btnQuit_Click(object sender, EventArgs e)
{
RSPool.Close();
this.Close();
}
}
}
Upvotes: 0
Views: 393