How to execute PowerShell script in C#

By FoxLearn 11/16/2024 2:45:53 AM   41.29K
Running PowerShell scripts or cmdlets from a C# Windows Forms Application involves using the System.Management.Automation namespace, which provides classes for interacting with PowerShell.

What is PowerShell?

Windows PowerShell is developed by Microsoft for the purpose of managing automation and configuring tasks.

If the Command Prompt has a fairly primitive scripting language, Powershell with the addition of Windows Scripting Host, VBScript, JScript has greatly increased the ability.

PowerShell is based primarily on the .NET Framework. Therefore, PowerShell is designed as an object-oriented utility and supports scripting languages.

How to Embed PowerShell Within a C# Application?

Creating a new Windows Froms Application project, then open your form designer. Next, We will drag TextBox, Button and Label controls from your Visual Studio Toolbox to your winform.

powershell c#

After completing the interface design, you need to install the System.Management.Automation from the Manage Nuget Packages to your project.

Here's an example demonstrating how to call PowerShell cmdlets from C#.

Adding a click event handler to the Run button allows you to run the powershell script that you enter from your TextBox control.

// c# run powershell commands
private void btnRun_Click(object sender, EventArgs e)
{
    txtOutput.Clear();
    // powershell c# cmdlet run
    using (PowerShell powerShell = PowerShell.Create()) // Create a PowerShell instance
    {
        powerShell.AddScript(txtInput.Text);
        // Add a cmdlet and parameters
        powerShell.AddCommand("Out-String");
        // Invoke the cmdlet
        Collection<PSObject> PSOutput = powerShell.Invoke();
        StringBuilder stringBuilder = new StringBuilder();
        // Output the results
        foreach (PSObject pSObject in PSOutput)
            stringBuilder.AppendLine(pSObject.ToString());
        txtOutput.Text = stringBuilder.ToString();
    }
}

First, Use PowerShell.Create() to create an instance of the PowerShell runtime, then use AddCommand("Get-Process") specifies the cmdlet you want to run.

How to run PowerShell scripts from C#?

Adding a click event handler to the Open button allows you to open the powershell script file, then execute the powershell script file.

// c# run powershell script
private void btnOpen_Click(object sender, EventArgs e)
{
    txtOutput.Clear();
    using (OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "PowerShell|*.ps1" })
    {
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            // powershell c# cmdlet run
            using (PowerShell powerShell = PowerShell.Create()) // Create a PowerShell instance
            {
                powerShell.AddScript(System.IO.File.ReadAllText(openFileDialog.FileName));
                // Add a cmdlet and parameters
                powerShell.AddCommand("Out-String");
                // Invoke the cmdlet
                Collection<PSObject> PSOutput = powerShell.Invoke();
                StringBuilder stringBuilder = new StringBuilder();
                // Output the results
                foreach (PSObject pSObject in PSOutput)
                    stringBuilder.AppendLine(pSObject.ToString());
                txtOutput.Text = stringBuilder.ToString();
            }
        }
    }
}

You can also get output from the PowerShell command after executing and reading data from the PSObject object.

To check for errors when calling PowerShell cmdlets from C#, you can use the HadErrors property of the PowerShell instance. If any errors occur during the execution, you can iterate through the Streams.Error collection to display the error details.

// Check for errors
if (powerShell.HadErrors)
{
    Console.WriteLine("Error encountered while executing PowerShell cmdlet.");
    foreach (var error in powerShell.Streams.Error)
    {
        Console.WriteLine(error.ToString());
    }
}

To call a PowerShell cmdlet with a name and parameters, you can use the AddCommand method to specify the cmdlet, and the AddParameter method to pass any parameters.

For example, to call Get-Process with the -Name parameter to filter by process name, you can write:

// Add a cmdlet and parameters (e.g., Get-Process with a specific name)
powerShell.AddCommand("Get-Process")
          .AddParameter("Name", "notepad");

How to use PowerShell in .NET Console Application

Similarly, you can easily call PowerShell from .Net Console application and pass the command as an argument as shown below.

// run powershell in c#
static void Main(string[] args)
{
    ProcessStartInfo processInfo = new ProcessStartInfo();
    processInfo.FileName = "powershell.exe";
    processInfo.Arguments = $@"& {args[0]}";
    processInfo.RedirectStandardError = true;
    processInfo.RedirectStandardOutput = true;
    processInfo.UseShellExecute = false;
    processInfo.CreateNoWindow = true;

    Process process = new Process();
    process.StartInfo = processInfo;
    process.Start();

    Console.WriteLine("Output - {0}", process.StandardOutput.ReadToEnd());
    Console.WriteLine("Errors - {0}", process.StandardError.ReadToEnd());
    Console.Read();
}

You can also create a method allows you to execute powershell cmdlets or powershell script through console application in c# as shown below.

void GetError()
{
    var script = @"C:\scripts\myscript.ps1";
    var startInfo = new ProcessStartInfo()
    {
        FileName = "powershell.exe",
        Arguments = $"-NoProfile -ExecutionPolicy unrestricted \"{script}\"",
        UseShellExecute = false
    };
    Process.Start(startInfo);
}

Through the example above, I hope you can integrate powershell cmdlets within your C# applications.