首页 > 解决方案 > 在 C# 中运行 Powershellscript

问题描述

我正在尝试通过 C# 在 Windows 窗体中运行 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]
}
}

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

这甚至可能吗?

谢谢你的帮助!

标签: c#windowsformswinformspowershell

解决方案


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

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

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


推荐阅读