I want to execute a Powershell script asynchronously in C#. I've used BeginInvoke
method but I can't get the output/errors even though I've attached delegates for them. Here is my C# code:
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
}
I have multiple Write-Output
statements in my script. However, the DataAdded
methods are never triggered. But they are triggered when I use the synchronous Invoke
method.
See this answer. To actually run it asynchronously, you need to make your method asynchronous too. You can do that by calling
Task.Factory.FromAsync(...)
to get aTask<PSObject>
for the asynchronous operation, then usingawait
.