Fallenour
Fallenour

Reputation: 72

how do I integrate powershell into C sharp

I've got all the scripts done, and I wrote out the entire C# GUI in Visual Studio Enterprise 2015.

I just need to get the button to launch a specific script when its clicked (Control.OnClick Method?).

I tried finding examples, but they were incredibly vague.

enter image description here

The hopeful outcome is as follows:

###   Begin Code   ###

##   C# psuedo code here   ##

//make C# bunifu Button 1 call script on click of button1

Invoke.OnClick Method (Or Correct option)

//Functional Example of an Invoke.OnClick Method Here doing something here. This is so I can learn and understand.

Place holder

//powershell equivalent
$SOCMonkeyDoStuff = Invoke-Item "C:\Powershell\Scripts\BecomeOneWithCodeMonkeys\Script.ps1


//Button Interaction in Powershell

$Title = "Task Menu"
$Caption = @"
1 - Get Running Services
2 - Get Top Processes
3 - Get Disk Utilization
Q - Quit

Select a choice:
"@

$coll = @()


$a = [System.Management.Automation.Host.ChoiceDescription]::new("&1 Services")
$a.HelpMessage = "Get Running Services"
$a | Add-Member -MemberType ScriptMethod -Name Invoke -Value {Get-service |     where {$_.status -eq "running"}} -force

$coll+=$a

And I know, yes this code already works, why not just do it in powershell? The reason is is I plan on turning it into a platform agnostic tool in the very near future so Linux and Windows can both use it, and Id like to remain as vendor neutral as possible. Additionally, I plan on exporting it as a .exe so that it can be installed anywhere.

Upvotes: 1

Views: 3182

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174545

You could create a function that takes the path to a PowerShell script as its argument, and then execute said script. Could be as simple as:

private void RunPSScript(string path)
{
    using (PowerShell ps = PowerShell.Create())
    {
        // add the script to the PowerShell instance
        ps.AddScript(path);

        // run it
        ps.Invoke();
    }
}

Then all you need is an event handler for the OnClick event of the button to invoke the function. I've never worked with the Bunifu library, so I don't know if OnClick is the right event name, but this is how it would look with Forms or WPF:

bunifuFlatButton1.OnClick += bunifuFlatButton_OnClick;

With the event handler looking something like:

private void Button1_Click(object sender, EventArgs e)
{
    string scriptPath;
    // assign value to scriptPath here

    // then invoke the method from before
    RunPSScript(scriptPath);
}

Remember to add a reference to the System.Management.Automation assembly in your project (basically the PowerShell API)

Upvotes: 3

Related Questions