在C#中运行Powershellscript

我试图在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 { ///  /// Der Haupteinstiegspunkt für die Anwendung. ///  [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] } } 

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

这有可能吗?

谢谢你的帮助!

您可以将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()); } } } 

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

请注意,按原样运行当前脚本只会声明您的Food函数,但实际上不会运行它。 确保脚本或C#代码中存在函数调用。