通过 C# Powershell 变量设置 [英] Set via C# Powershell Variable
问题描述
我必须在 PowerShell 中通过 C# 设置一个变量,并且必须再次在 Powershell 中通过 C# 使用该变量,到目前为止我的代码:
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
但是这个C#不行,我也累了:
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();
但这两者都不起作用.有人知道如何在 Powershell 中设置变量并始终通过 C# 在 Powershell 中使用它吗?
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#?
推荐答案
关于设置变量,你的第二个代码块按预期工作,以下是powershell中的快速测试设置$item到 FooBar,将其拉回并确认值正确:
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");
}
要从 C# 直接在 Powershell 上工作,以下应该可以解决问题:
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];
这篇关于通过 C# Powershell 变量设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!