[英]Run Powershellscript in C#
我試圖在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]
}
}
最后,我希望能夠只按下表單上的按鈕,然后讓它運行腳本,將其輸出到文本框。
這甚至可能嗎?
謝謝你的幫助!
您可以將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#代碼中存在函數調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.