1

How can I get the powershell variable $test from a c# application?

I tried it like this:

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 is null. But I filled it in powershell with an int (i.e. $test = 4).

4
  • 1
    Don't you need to use GetValue("$test") (with a $) instead? Commented Jan 23, 2015 at 12:01
  • This doesn't work either... I can call the function with the variable PSHome, this works. But not the variable I have set. Commented Jan 23, 2015 at 12:02
  • Might be a duplicate of: stackoverflow.com/questions/17467629/… Commented Jan 23, 2015 at 12:05
  • It's not. I have seen this post but the answer does not work. Commented Jan 23, 2015 at 12:07

1 Answer 1

3

Use $global:test=4 in script or run script in same scope. By default script run in its own scope, so any variable changed in script does not visible outside.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.