我正在从c#运行powershell脚本。
string scriptPath = "/script/myscript.ps1";
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptPath);
Collection<PSObject> results = pipeline.Invoke();
例如,如果下面是我的myscript.ps1文件;
$test=4
$test++
$test
如何在执行脚本后获得变量test
的值。我需要将这个值应用到我的c#程序中。
我知道我迟到了,但在您的脚本中,您需要在Powershell脚本中要返回的变量前面添加global:
,因此例如:
$global:test = 4
Powershell脚本中。在C#中,打开运行空间后,调用策略更改程序,设置管道,然后进行
var result = runspace.SessionStateProxy.PSVariable.GetValue("test");
string variable_to_return_from_ps_script = "test";
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
//
// here you write the code to invoke the PS script, pipeline, pass parameters etc...
// just like the code you already have
//
// and here's how you retrieve a variable test from PS
var out_var = runspace.SessionStateProxy.PSVariable.GetValue(variable_to_return_from_ps_script);
Console.WriteLine("Variable ${0} value is: ", variable_to_return_from_ps_script);
Console.WriteLine(out_var.ToString());