![](/img/trans.png)
[英]How to pass parameters to a powershell script using c# winforms?
[英]How to pass powershell parameters in c#
我正在嘗試使用 c# 傳遞 powershell 參數。 如何在 c# 中傳遞這些參數,以便它按預期執行。 function 是 Update-All,它通過變量 Name 是“測試示例”。 我要調用的命令是調用 function 以禁用該變量名稱“測試示例”。 提前致謝。
protected void Page_Load(object sender, EventArgs e)
{
TestMethod();
}
string scriptfile = "C:\\Users\\Desktop\\Test_Functions.ps1";
private Collection<PSObject> results;
public void TestMethod()
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
//Here's how you add a new script with arguments
Command myCommand = new Command(scriptfile);
CommandParameter testParam = new CommandParameter("Update-All Name 'test example'", "Function 'Disable'");
myCommand.Parameters.Add(testParam);
pipeline.Commands.Add(myCommand);
// Execute PowerShell script
results = pipeline.Invoke();
}
這個可以嗎? 答案與這篇文章類似
public void TestMethod()
{
string script = @"C:\Users\Desktop\Test_Functions.ps1";
StringBuilder sb = new StringBuilder();
PowerShell psExec = PowerShell.Create();
psExec.AddScript(script);
psExec.AddCommand("Update-All Name 'test example'", "Function 'Disable'");
Collection<PSObject> results;
Collection<ErrorRecord> errors;
results = psExec.Invoke();
errors = psExec.Streams.Error.ReadAll();
if (errors.Count > 0)
{
foreach (ErrorRecord error in errors)
{
sb.AppendLine(error.ToString());
}
}
else
{
foreach (PSObject result in results)
{
sb.AppendLine(result.ToString());
}
}
Console.WriteLine(sb.ToString());
}
結果/錯誤將打印在字符串生成器中供您查看
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.