Csharp/C#教程:将powershell变量值返回给c#应用程序分享


将powershell变量值返回给c#应用程序

我从c#运行powershell脚本。

string scriptPath = "/script/myscript.ps1"; Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(scriptPath); Collection results = pipeline.Invoke(); 

例如,如果我的myscript.ps1文件在下面;

 $test=4 $test++ $test 

如何在执行脚本后获取变量test值。 我需要为我的c#程序获得这个价值。

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

 $global:test = 4 

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

上述就是C#学习教程:将powershell变量值返回给c#应用程序分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

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

www.ctvol.com true Article Csharp/C#教程:将powershell变量值返回给c#应用程序分享

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1005088.html

(0)
上一篇 2021年12月28日 下午5:46
下一篇 2021年12月28日 下午5:47

精彩推荐