2

我正在从 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# 程序获取该值。

4

2 回答 2

4

我知道我迟到了,但是在您的脚本中,您需要global:在要在 Powershell 脚本中返回的变量前面添加,例如:

$global:test = 4

在 Powershell 脚本中。在 C# 中打开运行空间后,调用策略更改器,设置管道,您可以

var result = runspace.SessionStateProxy.PSVariable.GetValue("test");
于 2015-06-17T14:03:18.177 回答
-1
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());
于 2013-11-28T23:51:55.740 回答