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();
}
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 ...
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With