在C#中运行Powershell脚本

3

我正在尝试在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
}

我理解您的意思,我需要在 static 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]
}
}

最终,我希望能够在表单上只按一个按钮,然后运行脚本并将其输出到文本框中。这是否可行?感谢任何帮助!

2
你不能将PowerShell脚本转换为C#代码并直接使用吗?如果不行,可以查看这篇文章:https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/ - AndreasHassing
2
我使用System.Diagnostics.Process来运行PowerShell脚本。保存脚本并将PowerShell作为带有脚本位置参数的进程运行。https://msdn.microsoft.com/de-de/library/system.diagnostics.process.start(v=vs.110).aspx - kurdy
@AndreasHassing 嗯,确实是这样,但我对C#完全是个新手...不过这是未来的计划...现在我只需要尽快让它运行 :) - alex
那么,我链接的博客文章将帮助你实现这一点(或者@srsedate的答案,它看起来很像博客文章的压缩格式)。 - AndreasHassing
@alex,你应该能够使用stdout来输出PowerShell的结果。 - kurdy
显示剩余2条评论
1个回答

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());
        }
    }
}

在这个例子中,您可能更好地利用传入的事件参数,并进行一些更好的错误处理和输出日志记录,但这应该能让您走上正确的道路。
请注意,按原样运行当前脚本将仅声明您的“Food”函数,但不会实际运行它。请确保在您的脚本或C#代码中有一个函数调用。

我刚刚在我的ps1脚本底部添加了食物,你能告诉我如何将输出发送到文本框吗?顺便感谢你的回答:D - alex
运行调试器,触发断点,查看 output 的值。然后,添加一些逻辑来操作该集合中的项。您可能需要设置文本框对象的 Text 属性。 - srbrills
1
如果我理解你的后续问题正确,item.ToString()将具有PowerShell脚本返回的值。从中获取返回值并将其放入文本框中,类似于:myTextBox.Text = item.ToString() - AndreasHassing
嗨,我按照你在解决方案中建议的方法尝试了一下,但是我遇到了多个错误。我遇到的第一个错误是在带有throw $"...."的那一行,它告诉我类型需要类似于system.Exception的东西..?你是否也遇到了同样的错误?这一行还需要加上;吗? - alex
@alex 对不起,我已经更新了原始帖子。 - srbrills

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接