How to call a powershell script from resources on windows form

JonathanWood 1 Reputation point
2021-03-01T22:21:48.663+00:00

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
    2021-03-02T08:29:32.897+00:00

    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.

    0 comments No comments