c# - 如何在c#中传递powershell参数
问题描述
我正在尝试使用 c# 传递 powershell 参数。如何在 c# 中传递这些参数,以便它按预期执行。该函数是 Update-All,它传递变量 Name,即“测试示例”。我要调用的命令是调用函数以禁用该变量名称“测试示例”。提前致谢。
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());
}
结果/错误将打印在字符串生成器中供您查看
推荐阅读
- azure - 在 Azure 数据工厂中获取历史数据复制的日期
- sql - Presto - 联合和限制
- c - 如何修复 C 中的错误“表达式不是函数定位器”?
- flutter - Dart:如何强制对变量进行字符串插值
- c# - 获取 HTTP 标头值
- google-data-studio - 在数据工作室中按两个或多个日期过滤不同的日期列
- c# - gembox电子表格计算方法不可用
- python-3.x - RDS boto如何使用数据库DEFAULT值
- python - Python selenium - 多处理 - 如何关闭已分配进程的浏览器?
- c++ - “整数常量太大以至于它是无符号的”编译器警告理由