簡體   English   中英

將Powershell變量值返回給C#應用程序

[英]Return powershell variable value to c# application

我正在從C#運行Powershell腳本。

string scriptPath = "/script/myscript.ps1";
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptPath);
Collection<PSObject> results = pipeline.Invoke(); 

例如,如果我的myscript.ps1文件在下面;

$test=4
$test++
$test

執行腳本后如何獲取變量test值。 我需要為我的C#程序獲取該值。

我知道我來晚了,但是在您的腳本中,您需要在Powershell腳本中要返回的變量前面添加global: ::

$global:test = 4

在Powershell腳本中。 打開運行空間后,在C#中,調用策略更改器,設置pipline,然后執行

var result = runspace.SessionStateProxy.PSVariable.GetValue("test");
string variable_to_return_from_ps_script = "test"; 

// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

//
// here you write the code to invoke the PS script, pipeline, pass parameters etc...
// just like the code you already have
//

// and here's how you retrieve a variable test from PS
var out_var = runspace.SessionStateProxy.PSVariable.GetValue(variable_to_return_from_ps_script);
Console.WriteLine("Variable ${0} value is: ", variable_to_return_from_ps_script);
Console.WriteLine(out_var.ToString());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM