如何从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");
resultVariable
是null
。但我在powershell中用int填充它(即$ test = 4)。
答案 0 :(得分:3)
在脚本中使用$global:test=4
或在同一范围内运行脚本。默认情况下,脚本在其自己的作用域中运行,因此在脚本中更改的任何变量都不会在外部显示。