How to call a powershell script from resources on windows form

JonathanWood 1 Reputation point

I am making a Windows Form app in Visual Studio using C#, I loaded my PowerShell script into a folder in my resources, but I don't know how to call the script when a button is clicked on the main form.

This is what I have:

private void buttonDebloater_Click(object sender, EventArgs e)
// Runs Windows Debloater

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,866 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,791 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,621 Reputation points

    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  
        // 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  
        // convert the script result into a single string  
        StringBuilder stringBuilder = new StringBuilder();  
        foreach (PSObject obj in results)  

    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.

    0 comments No comments