How to run powershell commands in C#

By FoxLearn 11/16/2024 2:53:30 AM   394
You can run PowerShell commands in c# by using the System.Management.Automation namespace, which provides classes for interacting with PowerShell from managed code.

First, You need to add a reference to System.Management.Automation in your C# project.

How to run powershell in C#?

You can create an instance of the PowerShell class and run commands.

For example:

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();
    }
}

We create an instance of PowerShell, then we add the PowerShell command or script using the AddScript method.

If you want to invoke a PowerShell cmdlet, you can use AddCommand in place of AddScript.

// Add the Get-Process cmdlet, powershell c# cmdlet run
powershell.AddCommand("Get-Process");
// Execute the command and capture the output
var results = powershell.Invoke();

Next, We invoke the command asynchronously using BeginInvoke, then we wait for the command to complete by checking the IsCompleted property.

Once the command is completed, we retrieve the results using EndInvoke, we will display the result in our 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.

You can also run more complex PowerShell scripts or commands that require parameters.

For example:

// Add a script with parameters
powershell.AddScript("$param1 = 'Hello'; $param2 = 'World'; Write-Output $param1 $param2");

// Execute the script
var results = powershell.Invoke();

In this case, the script defines two variables ($param1 and $param2), and outputs them together.