[英]How to pass powershell parameters in c#
I'm trying to pass powershell parameters using c#.我正在尝试使用 c# 传递 powershell 参数。 How can I pass these parameters in c# so that it will execute as expected.如何在 c# 中传递这些参数,以便它按预期执行。 The function is Update-All which passes the variable Name that is 'test example'. function 是 Update-All,它通过变量 Name 是“测试示例”。 The command that I will like to invoke is to call the function to Disable that variable Name 'test example.'我要调用的命令是调用 function 以禁用该变量名称“测试示例”。 Thanks in Advance.提前致谢。
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();
}
Is this okay?这个可以吗? The answer is similar to this post答案与这篇文章类似
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());
}
The results/errors will be printed in the string builder for you to see结果/错误将打印在字符串生成器中供您查看
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.