Button to run PowerShell script

WoodChip1650

New member
Joined
Mar 2, 2021
Messages
1
Programming Experience
Beginner
I am new to C# and Visual Studio, however, I have a pretty good app going, however, I can't figure out how to make a PowerShell script run when a button is clicked off of my main WinForm.
This is what I have, also I loaded the script in the solutions under a folder called "Scripts" which I also don't know how to call it from that location. Thank s in advance for the help.

C#:
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;

Debloater Button:
private void buttonDebloater_Click(object sender, EventArgs e)
        {
            // Runs Windows Debloater
            PowerShell ps = PowerShell.Create();
            ps.AddScript(@"C:\Users\JonathanWood\OneDrive - KLJWTech LLC\Visual Studios\SuperAdminApp\Scrips\Windows10Debloater.ps1");
            ps.Invoke();
        }
 
If should collect the results from that invocation to see if it successfully ran. If that script that you are loading is interactive -- e.g. it prompts for inputs or trying to bring up dialog boxes, then you'll have to go to the next level of PowerShell hosting. See link below:


If you don't want to go through the trouble of hosting PowerShell, consider just using Process.Start() to start "powershell.exe" or "pwsh.exe" and pass in the path to your script.
 
Back
Top Bottom