我正在从 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# 程序中。
最佳答案
我知道我迟到了,但是在您的脚本中,您需要在 Powershell 脚本中要返回的变量前面添加 global:
,例如:
$global:test = 4
在 Powershell 脚本中。在 C# 中,打开运行空间后,调用策略更改器,设置 pipline,您可以这样做
var result = runspace.SessionStateProxy.PSVariable.GetValue("test");
关于c# - 将 powershell 变量值返回给 c# 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17467629/