Windows Forms: How to run Script Windows Power Shell in C#

This post shows you How to run Script Windows Power Shell in C# .NET Windows Forms Application

Creating a new Windows Froms Application project, then drag TextBox, Button and Label controls from the visual studio toolbox to your winform.

c# winform powershell

To play the demo, you need to install the System.Management.Automation from the Manage Nuget Packages to your project.

The System.Management.Automation library helps you run powershell in c# winform.

Next, Create the RunScript method allows you to run the command. You can input get-process, get-service...etc, then write c# run powershell command and get output as shown below.

private string RunScript(string script)
    Runspace runspace = RunspaceFactory.CreateRunspace();
    Pipeline pipeline = runspace.CreatePipeline();
    Collection<PSObject> results = pipeline.Invoke();
    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject ps in results)
    return stringBuilder.ToString();

You can use c# powershell runspace to run powershell script from c# with parameters.

Adding click event handler to the Run button allows you to run powershell script from c# windows form.

private void btnRun_Click(object sender, EventArgs e)
    txtResult.Text = RunScript(txtComand.Text);

Related Posts