Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过C#Powershell变量设置_C#_Variables_Powershell - Fatal编程技术网

通过C#Powershell变量设置

通过C#Powershell变量设置,c#,variables,powershell,C#,Variables,Powershell,我必须在PowerShell中通过C#设置一个变量,并且必须再次在PowerShell中通过C#使用该变量,到目前为止,我的代码是: 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"); InvokeC

我必须在PowerShell中通过C#设置一个变量,并且必须再次在PowerShell中通过C#使用该变量,到目前为止,我的代码是:

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);
在这种情况下,输出应为: 产品

但是这个C#不起作用,我也很累:

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();
但两者都不起作用。
有人知道我如何在Powershell中设置变量并始终通过C#?

在设置变量方面,您的第二个代码块按预期工作,下面是在Powershell中将$item快速测试设置为FooBar,将其向后拉并确认值正确:

[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");
}
要从C#直接在Powershell上工作,请执行以下操作:

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];
另一种方法

设置变量:

SessionState.PSVariable.Set("TestVar", "1");
object myvar = GetVariableValue("TestVar");
获取变量:

SessionState.PSVariable.Set("TestVar", "1");
object myvar = GetVariableValue("TestVar");

谢谢你的回答。但我不想用C#表示变量。我想在powershell中设置它,然后通过C#在powershell中使用它。