Hi JonathanWood-6554,
First, you need to add a reference to the System.Management.Automation assembly.
Then, add the following 'using' statements to import the required types:
using System.Management.Automation;
using System.Management.Automation.Runspaces;
Here is code example about running PowerShell scripts from winforms you can refer to.
private void button1_Click(object sender, EventArgs e)
{
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
// create a pipeline and feed it the script
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(File.ReadAllText(@"C:\Users\Desktop\MyScript.ps1"));//change to your PowerShell script file path
// execute the script
Collection<PSObject> results = pipeline.Invoke();
// close the runspace
runspace.Close();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
Console.WriteLine(stringBuilder.ToString());
Best Regards,
Daniel Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.