将 powershell 变量值返回给 C# 应用程序 [英] Return powershell variable value to c# application
本文介绍了将 powershell 变量值返回给 C# 应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从 c# 运行 powershell 脚本.
I am running powershell script from 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 文件在下面;
for example if my myscript.ps1 file below;
$test=4
$test++
$test
执行脚本后如何获取变量test
的值.我需要为我的 c# 程序获取该值.
How to get the variable test
value after executing the script. I need to get that value to my c# program.
推荐答案
我知道我迟到了,但是在你的脚本中,你需要在你想要的变量前面添加 global:
在 Powershell 脚本中返回,例如:
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:
$global:test = 4
在 Powershell 脚本中.在 C# 中打开运行空间后,调用策略更改器,设置管道,就可以了
in Powershell script. In C# after you open the runspace, invoke the policy changer, set up the pipline, you do
var result = runspace.SessionStateProxy.PSVariable.GetValue("test");
这篇关于将 powershell 变量值返回给 C# 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文