How to run powershell commands in C#

By FoxLearn 7/6/2024 3:01:11 AM   163
You can run PowerShell commands in c# by using the System.Management.Automation namespace, which provides classes for interacting with PowerShell from managed code.

Here's a basic example of how to run powershell in c#

using System;
using System.Management.Automation;

// powershell c# command
class Program
{
    // run powershell in c#
    static void Main(string[] args)
    {
        // Create an instance of PowerShell
        using (PowerShell PowerShellInstance = PowerShell.Create())
        {
            // Add the script/command you want to run
            PowerShellInstance.AddScript("Get-Process");

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

            // Wait for the command to complete
            while (!asyncResult.IsCompleted)
            {
                Console.WriteLine("Waiting for PowerShell to finish...");
                System.Threading.Thread.Sleep(1000);
            }

            Console.WriteLine("Command completed.");

            // Get the results of the command
            foreach (PSObject result in PowerShellInstance.EndInvoke(asyncResult))
            {
                Console.WriteLine(result.ToString());
            }
        }

        Console.ReadLine();
    }
}

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.