2

I am running powershell script from c#.

string scriptPath = "/script/myscript.ps1";
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptPath);
Collection<PSObject> results = pipeline.Invoke(); 

for example if my myscript.ps1 file below;

$test=4
$test++
$test

How to get the variable test value after executing the script. I need to get that value to my c# program.

2 Answers 2

4

I know I am late to this, but in your script, you need to add global: in front of the variable you want to return in the Powershell script, so for example:

$global:test = 4

in Powershell script. In C# after you open the runspace, invoke the policy changer, set up the pipline, you do

var result = runspace.SessionStateProxy.PSVariable.GetValue("test");
Sign up to request clarification or add additional context in comments.

Comments

-1
string variable_to_return_from_ps_script = "test"; 

// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

//
// here you write the code to invoke the PS script, pipeline, pass parameters etc...
// just like the code you already have
//

// and here's how you retrieve a variable test from PS
var out_var = runspace.SessionStateProxy.PSVariable.GetValue(variable_to_return_from_ps_script);
Console.WriteLine("Variable ${0} value is: ", variable_to_return_from_ps_script);
Console.WriteLine(out_var.ToString());

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.