4

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
  • You've got a using statement with an asynchronous BeginInvoke. The host PowerShell object is going to get disposed before the command pipeline completes. Commented Dec 15, 2014 at 8:42

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.