在C#中运行Powershellscript

时间:2018-06-12 13:40:13

标签: c# windows forms winforms powershell

我正在尝试通过Windows窗体中的C#运行PowerShell脚本。

问题是我有两个枚举,我无法在代码中获取它们:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

namespace WindowsFormsApp6
{
    static class Program
    {
        /// <summary>
        /// Der Haupteinstiegspunkt für die Anwendung.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }   *here
}

我理解,我是否必须在静态void下添加以下内容? (在*这里):

 using (PowerShell PowerShellInstance = PowerShell.Create())
 {
 }

然后,我将它粘贴在那里吗?

但当然不是那么容易;我谷歌了,但我不明白为了让它发挥作用我必须做些什么......

Enum RandomFood
{#Add Food here:
Pizza
Quesedias
Lasagne
Pasta
Ravioli
}

Enum Meat
{#Add Food here:
Steak
Beaf
Chicken
Cordonbleu
}

function Food {

Clear-Host
  $Foods =  [Enum]::GetValues([RandomFood]) | Get-Random -Count 6
  $Foods += [Enum]::GetValues([Meat]) | Get-Random -Count 1

$foodsOfWeek = $Foods | Get-Random -Count 7
Write-Host `n "Here is you'r List of Meals for this week :D" `n
foreach ($day in [Enum]::GetValues([DayOfWeek])) {
    ([string]$day).Substring(0, 3) + ': ' + $foodsOfWeek[[DayOfWeek]::$day]
}
}

最后,我希望能够只按下表单上的按钮,然后运行脚本将其输出到文本框。

这甚至可能吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您可以将PowerShell脚本放入单独的文件中,并在绑定事件上调用它。

// When a button is clicked...
private void Button_Click(object sender, EventArgs e)
{
    // Create a PS instance...
    using (PowerShell instance = PowerShell.Create())
    {
        // And using information about my script...
        var scriptPath = "C:\\myScriptFile.ps1";
        var myScript = System.IO.File.ReadAllText(scriptPath);
        instance.AddScript(myScript);
        instance.AddParameter("param1", "The value for param1, which in this case is a string.");

        // Run the script.
        var output = instance.Invoke();

        // If there are any errors, throw them and stop.
        if (instance.Streams.Error.Count > 0)
        {
            throw new System.Exception($"There was an error running the script: {instance.Streams.Error[0]}");
        }

        // Parse the output (which is usually a collection of PSObject items).
        foreach (var item in output)
        {
            Console.WriteLine(item.ToString());
        }
    }
}

在这个例子中,你可能会更好地利用传入的事件参数,并执行一些更好的错误处理和输出日志记录,但这应该让你走上正确的道路。

请注意,按原样运行当前脚本只会声明您的食物功能,但实际上并未运行它。确保脚本或C#代码中有函数调用。