Windows Forms: How to execute PowerShell script in C#

This post shows you How to execute PowerShell script file or cmdlets from C# .NET Windows Forms Application.

What is PowerShell?

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

It is a scripting language provided by Microsoft. 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.

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();
    using (PowerShell powerShell = PowerShell.Create())
    {
        powerShell.AddScript(txtInput.Text);
        powerShell.AddCommand("Out-String");
        Collection<PSObject> PSOutput = powerShell.Invoke();
        StringBuilder stringBuilder = new StringBuilder();
        foreach (PSObject pSObject in PSOutput)
            stringBuilder.AppendLine(pSObject.ToString());
        txtOutput.Text = stringBuilder.ToString();
    }
}

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.

private void btnOpen_Click(object sender, EventArgs e)
{
    txtOutput.Clear();
    using (OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "PowerShell|*.ps1" })
    {
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            using (PowerShell powerShell = PowerShell.Create())
            {
                powerShell.AddScript(System.IO.File.ReadAllText(openFileDialog.FileName));
                powerShell.AddCommand("Out-String");
                Collection<PSObject> PSOutput = powerShell.Invoke();
                StringBuilder stringBuilder = new StringBuilder();
                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.

Using 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.

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 into the .net application.