Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create C# async powershell method?

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();
    }
like image 750
Ryan Currah Avatar asked Jul 14 '13 15:07

Ryan Currah


People also ask

What is C used to create?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C easy for beginners?

C is not just what students use to learn programming. It's not an academic language. And I would say it's not the easiest language, because C is a rather low level programming language. Today, C is widely used in embedded devices, and it powers most of the Internet servers, which are built using Linux.


1 Answers

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.

like image 90
SLaks Avatar answered Sep 16 '22 14:09

SLaks