How to run Script Windows Power Shell in C#
By FoxLearn 7/18/2024 3:30:36 AM 3.35K
Open your Visual Studio, then create a new Windows Forms Application project.
How to run Script Windows Power Shell in C#
Next, Drag and drop the TextBox, Button and Label controls from the Visual studio toolbox to your winform.
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); }
You can also use the System.Diagnostics.Process
class to execute PowerShell.exe and pass the script file as an argument.
private void btnRun_Click(object sender, EventArgs e) { string scriptPath = @"C:\Script.ps1"; // Path to your PowerShell script // Create a process start info ProcessStartInfo psi = new ProcessStartInfo { FileName = "powershell.exe", Arguments = $"-ExecutionPolicy Bypass -File \"{scriptPath}\"", RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; // Create the process Process process = new Process { StartInfo = psi }; // Start the process process.Start(); // Read the output and errors if needed string output = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); // Wait for the process to exit process.WaitForExit(); }
In this example when the user clicks a button, it executes the PowerShell script.
The PowerShell script runs with the -ExecutionPolicy Bypass
argument to bypass the PowerShell script execution policy, and -File
to specify the script file to execute.