2013-07-04 2 views
2

Я запускаю сценарий powershell с C#.Возвращает значение переменной powershell для приложения C#

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#.

ответ

0
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()); 
4

Я знаю, что поздно, но в сценарии, вам нужно добавить global: перед переменной, которую вы хотите, чтобы вернуться в сценарий Powershell, так, например:

$global:test = 4 

в сценарии Powershell. В C# после того, как вы откроете пробел, вызовите переключатель изменения политики, настройте трубопровод, вы делаете

var result = runspace.SessionStateProxy.PSVariable.GetValue("test"); 
Смежные вопросы