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#?
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];
Another way to do it.
Set variable:
SessionState.PSVariable.Set("TestVar", "1");
Get variable:
object myvar = GetVariableValue("TestVar");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With