This works in a console app:
using (PowerShell powershell = PowerShell.Create())
{
powershell.AddScript("1..10 | foreach {$_ ; start-sleep -milli 500}");
var output = new PSDataCollection<PSObject>();
output.DataAdded += delegate(object sender, DataAddedEventArgs e)
{
Console.WriteLine(output[e.Index]);
var myp = (PSDataCollection<PSObject>)sender;
Collection<PSObject> results = myp.ReadAll();
};
powershell.InvocationStateChanged += delegate(object sender, PSInvocationStateChangedEventArgs e)
{
if (e.InvocationStateInfo.State == PSInvocationState.Completed)
{
// Clean up
}
};
IAsyncResult asyncResult = powershell.BeginInvoke<PSObject, PSObject>(null, output);
asyncResult.AsyncWaitHandle.WaitOne();
}
If you don't somehow synchronize or comeback later and wait for the invoke to finish, the PowerShell engine shuts down because powershell.Dispose()
gets called as it falls out of your using {}
scope.