c# - 在 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]
}
}
最后,我希望能够只按表单上的一个按钮,然后让它运行将其输出到文本框的脚本。
这甚至可能吗?
谢谢你的帮助!
解决方案
您可以将 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# 代码中有函数调用。
推荐阅读
- sql-server - 如何将数据导入 CTE 并进行更新
- python - Python从满足特定条件的列表中查找数字
- javascript - 问题 - 如何在 Puppeteer 中传递“RegExp Object ??
- actions-on-google - 如何向用户发送 Google 助理操作的推送通知?
- r - R 如果滞后条件匹配,则用 NA 填充新列
- mysql - 错误:无法添加外键约束-
- java - Android DAO 添加查询“'@Query 不适用于字段”
- flutter - 是否可以在颤振引擎中的颤振引擎删除本机闪屏之前运行初始化代码
- ios - 识别哪个 UIImageView 被点击并在数组中获取它的索引
- elasticsearch - min_score 排除分数较高的文档