How to create C# async powershell method?
async-await, asynchronous, c#, powershell
Solution
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`.
Problem
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(); } ```