如何将PowerShell集成到C sharp

时间:2017-02-27 15:56:38

标签: c# visual-studio powershell imgur

我已完成所有脚本,并在Visual Studio Enterprise 2015中写出了整个C#GUI。

我只需要点击按钮即可启动特定脚本(Control.OnClick方法?)。

我试着找到例子,但是他们非常模糊。

enter image description here

有希望的结果如下:

###   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

我知道,是的,这段代码已经有效了,为什么不在powershell中做呢?原因是我计划在不久的将来将其变成一个平台无关的工具,因此Linux和Windows都可以使用它,并且Id希望尽可能保持供应商中立。此外,我计划将其导出为.exe,以便可以安装在任何地方。

1 个答案:

答案 0 :(得分:3)

您可以创建一个函数,将PowerShell脚本的路径作为其参数,然后执行所述脚本。可以这么简单:

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

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

然后你需要的是一个事件处理程序,用于调用该函数的按钮的OnClick事件。我从未使用过Bunifu库,因此我不知道OnClick是否是正确的事件名称,但这是使用Forms或WPF的样子:

bunifuFlatButton1.OnClick += bunifuFlatButton_OnClick;

事件处理程序看起来像:

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

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

请记住在项目中添加对System.Management.Automation程序集的引用(基本上是PowerShell API)

相关问题