7

I have to set via C# a variable in PowerShell and have to use that variable via C# in Powershell again, my code so far:

var command = string.Format("$item = Invoke-RestMethod {0} ", "http://services.odata.org/OData/OData.svc/?`$format=json");
var command2 = string.Format("$item.value[0].name");
InvokeCommand.InvokeScript(command);
object namesOne= InvokeCommand.InvokeScript(command2);

In this case the output should be: Products

But this C# doesn't work, i tired also:

Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
Pipeline pipeline = runSpace.CreatePipeline();

Command invoke = new Command("Invoke-RestMethod");
invoke.Parameters.Add("Uri", "http://services.odata.org/OData/OData.svc/?`$format=json");
pipeline.Commands.Add(invoke);

runSpace.SessionStateProxy.SetVariable("item", pipeline.Invoke());
var a = runSpace.SessionStateProxy.PSVariable.GetValue("item");
Command variable = new Command("Write-Host $item");

pipeline.Commands.Add(variable);
var output = pipeline.Invoke();

But it works neither. Has someone an idea how I could set a variable in Powershell and can work with it in Powershell always via C#?

2 Answers 2

7

In regards to setting a variable, your second code block works as expected, the following is a quick test setting $item in powershell to FooBar, pulling this back and confirming that the value is correct:

[Test]
public void PowershellVariableSetTest()
{
    var runSpace = RunspaceFactory.CreateRunspace();
    runSpace.Open();

    runSpace.SessionStateProxy.SetVariable("item", "FooBar");
    var a = runSpace.SessionStateProxy.PSVariable.GetValue("item");

    Assert.IsTrue(a.ToString() == "FooBar");
}

To work directly on Powershell from C#, the following should do the trick:

var command = string.Format("$item = Invoke-RestMethod {0} ", "http://services.odata.org/OData/OData.svc/?`$format=json");
var command2 = string.Format("$item.value[0].name");

var powershell = PowerShell.Create();
powershell.Commands.AddScript(command);
powershell.Commands.AddScript(command2);
var name = powershell.Invoke()[0];
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer. But I don't want to get the variable in C#. I want to set it in powershell and then use it in powershell via C#.
3

Another way to do it.

Set variable:

SessionState.PSVariable.Set("TestVar", "1");

Get variable:

object myvar = GetVariableValue("TestVar");

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.