How to run powershell commands in C#

You can run PowerShell commands in c# .net by using the System.Management.Automation namespace, which provides classes for interacting with PowerShell from managed code.

Here's a basic example of how you can execute PowerShell commands in C#

using System;
using System.Management.Automation;

class Program
    static void Main(string[] args)
        // Create an instance of PowerShell
        using (PowerShell PowerShellInstance = PowerShell.Create())
            // Add the script/command you want to run

            // Invoke the command asynchronously.
            var asyncResult = PowerShellInstance.BeginInvoke();

            // Wait for the command to complete
            while (!asyncResult.IsCompleted)
                Console.WriteLine("Waiting for PowerShell to finish...");

            Console.WriteLine("Command completed.");

            // Get the results of the command
            foreach (PSObject result in PowerShellInstance.EndInvoke(asyncResult))


1. We create an instance of PowerShell.

2. We add the PowerShell command or script using the AddScript method.

3. We invoke the command asynchronously using BeginInvoke.

4. We wait for the command to complete by checking the IsCompleted property.

Once the command is completed, we retrieve the results using EndInvoke.

Finally, we display the results in the console.

You can replace "Get-Process" with any PowerShell command or script you want to execute. Make sure to handle errors and exceptions appropriately in your production code.