Question:
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:
1 2 3 4 5 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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#?
Answer:
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
[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:
1 2 3 4 5 6 7 8 |
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]; |