简体   繁体   English

将Powershell变量值返回给C#应用程序

[英]Return powershell variable value to c# application

I am running powershell script from c#. 我正在从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(); 

for example if my myscript.ps1 file below; 例如,如果我的myscript.ps1文件在下面;

$test=4
$test++
$test

How to get the variable test value after executing the script. 执行脚本后如何获取变量test值。 I need to get that value to my c# program. 我需要为我的C#程序获取该值。

I know I am late to this, but in your script, you need to add global: in front of the variable you want to return in the Powershell script, so for example: 我知道我来晚了,但是在您的脚本中,您需要在Powershell脚本中要返回的变量前面添加global: ::

$global:test = 4

in Powershell script. 在Powershell脚本中。 In C# after you open the runspace, invoke the policy changer, set up the pipline, you do 打开运行空间后,在C#中,调用策略更改器,设置pipline,然后执行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM