Powershell C# asynchronous execution

2019-06-24 07:12发布

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.

1条回答
对你真心纯属浪费
2楼-- · 2019-06-24 08:05

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 a Task<PSObject> for the asynchronous operation, then using await.

查看更多
登录 后发表回答