I'd like to invoke a powershell script, capture the write-output information as it becomes available and add it to a table in the applications database. The reason for this is so that I can poll this information using Angular and display the powershell output to the end user via the web interface -Similiar to the console log you get when you spin up a VM on AWS.
Another user has already posted this question and has accepted the below answer, being someone with little async programming experience could someone help me out by elaborating on the accepted answer?
https://stackoverflow.com/questions/27478729/powershell-c-sharp-asynchronous-execution#=
Accepted Answer:
you need to make your method asynchronous too. You can do that by calling Task.Factory.FromAsync(...) to get a Task for the asynchronous operation, then using await.
using(ps=PowerShell.Create())
{
PSDataCollection<PSObject> output=new PSDataCollection<PSObject>();
output.DataAdded+=output_DataAdded;
ps.AddScript(RenewalScript);
SecureString ss = new SecureString();
for (int i = 0; i < Password.Length; i++)
ss.AppendChar(Password.ElementAt(i));
PSCredential cred = new PSCredential(Username, ss);
ps.AddParameter("Credential", cred);
ps.AddParameter("BuildServer", Server);
ps.AddParameter("CAServer", CAServer);
ps.AddParameter("CAName", CAName);
ps.Streams.Error.DataAdded += Error_DataAdded;
var result=ps.BeginInvoke<PSObject, PSObject>(null, output);
}
void output_DataAdded(object sender, DataAddedEventArgs e)
{
//display output in UI
}
void Error_DataAdded(object sender, DataAddedEventArgs e)
{
//display error message in UI
}