12

So I want to create a way to run a powershell script asynchronously. The below code is what I have so far, but it doesn't seem to be async because it locks up the application and the output is incorrect.

    public static string RunScript(string scriptText)
    {
        PowerShell ps = PowerShell.Create().AddScript(scriptText);

        // Create an IAsyncResult object and call the
        // BeginInvoke method to start running the 
        // pipeline asynchronously.
        IAsyncResult async = ps.BeginInvoke();

        // Using the PowerShell.EndInvoke method, get the
        // results from the IAsyncResult object.
        StringBuilder stringBuilder = new StringBuilder();
        foreach (PSObject result in ps.EndInvoke(async))
        {
            stringBuilder.AppendLine(result.Methods.ToString());
        } // End foreach.

        return stringBuilder.ToString();
    }

2 Answers 2

9

You are calling it asynchronously.

However, you are then defeating the purpose by synchronously waiting for the asynchronous operation to finish, by calling EndInvoke().

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.

3 Comments

Forgive my ignorance, my understanding of making the method async dont I just make the method start like... public async static Task<string> RunScriptAsync(string scriptText)
@user1843359: Yes, and use the await keyword to wait for asynchronous operations to finish.
I had results with: await Task.Factory.FromAsync(_ps.BeginInvoke(), pResult => _ps.EndInvoke(pResult));
0

This may not have been available when this post was made, but considering it is a top google search result it may be helpful to know that there is now an InvokeAsync command.

PSDataCollection<PSObject> connectionResult = await ps1.InvokeAsync();

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.