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();
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(script);
    pipeline.Commands.Add("Out-String");
    Collection<PSObject> results = pipeline.Invoke();
    runspace.Close();
    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject ps in results)
        stringBuilder.AppendLine(ps.ToString());
    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.Clear();
    txtResult.Text = RunScript(txtComand.Text);
}

Related