Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set via C# Powershell Variable

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#?

like image 753
Philip Giuliani Avatar asked Oct 30 '13 09:10

Philip Giuliani


2 Answers

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];
like image 94
JMK Avatar answered Oct 18 '22 05:10

JMK


Another way to do it.

Set variable:

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

Get variable:

object myvar = GetVariableValue("TestVar");
like image 39
Chunhui Deng Avatar answered Oct 18 '22 04:10

Chunhui Deng