C# 从 powershell 脚本获取变量

C# get variable from powershell script

如何从 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 或在同一范围内使用 运行 脚本。默认情况下,脚本 运行 在其自己的范围内,因此在脚本中更改的任何变量在外部都不可见。