如何从C#应用程序中获取Powershell变量$ test?

我这样尝试过:

RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();

RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

Pipeline pipeline = runspace.CreatePipeline();
//Here's how you add a new script with arguments
Command myCommand = new Command(scriptFile);
CommandParameter testParam = new CommandParameter("key", "value");
CommandParameter testParam2 = new CommandParameter("key", "value");
CommandParameter testParam3 = new CommandParameter("key", "value");
myCommand.Parameters.Add(testParam);
myCommand.Parameters.Add(testParam2);
myCommand.Parameters.Add(testParam3);

pipeline.Commands.Add(myCommand);

// Execute PowerShell script
var results = pipeline.Invoke();
var resultVariable = runspace.SessionStateProxy.PSVariable.GetValue("test");
resultVariablenull。但是我在powershell中用一个int填充它(即$ test = 4)。

最佳答案

在脚本中使用$global:test=4或在相同范围内运行脚本。默认情况下,脚本在其自己的范围内运行,因此脚本中更改的任何变量在外部都不可见。

关于c# - C#从Powershell脚本获取变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28109360/

10-12 18:40