2017-09-26 27 views
0

我在C#中的Powershell中運行命令,並且需要讀取var的內容。我嘗試了所有我在網上找到的解決方案,但目前爲止還沒有成功。從C#中的powershell獲取var#

這裏是我當前的代碼(有一些「嘗試」仍然包括)

string output; 

var nodePath = HttpContext.Server.MapPath("~/.bin/node.exe"); 
var mjmlFromStringCmd = HttpContext.Server.MapPath("~/.bin/mjmlFromString"); 
var mjmlTemplate = System.IO.File.ReadAllText(HttpContext.Server.MapPath("~/.bin/test.mjml")); 
var command = $"$htmlOutput = {nodePath} {mjmlFromStringCmd} -c '{mjmlTemplate}'"; 

var powershell = PowerShell.Create(); 
powershell.Commands.AddScript(command); 
var t = powershell.Invoke(); // I tired using powershell.Invoke()[0] because a post on SO said it might work, but the array returned by Invoke contains 0 elements 
var bf = powershell.Runspace.SessionStateProxy.PSVariable.Get("htmlOutput"); // I tried to get the var using two different methods, both give an empty value 
var htmlOutput = powershell.Runspace.SessionStateProxy.GetVariable("htmlOutput"); 
output = htmlOutput as string; 

,這裏是執行的PowerShell命令

$htmlOutput = C:\\Perso\\Websites\\FoyerRural\\.bin\\node.exe C:\\Perso\\Websites\\FoyerRural\\.bin\\mjmlFromString -c '****lots of content - MJML template (xml-style markup)****' 

如果我直接在PowerShell提示符下運行命令, $htmlOutput var獲得它的價值,我可以通過致電打印

$htmlOutput 

是否有一些與C##powershell類錯過了?如何獲得C#中powershell htmlOutput變量的值?

+1

如何使用環境變量? –

+0

你會怎麼做?我查了一下,但我找不到有關它的很多信息... 我試圖將我的var初始化爲'$ global:htmlOutput',但它沒有改變任何東西。我嘗試像我以前那樣獲取var,並且我還嘗試在調用'GetVariable'的var名稱之前添加'global:'...仍然獲得空值: -/ – Wndrr

+0

讀取/寫入環境變量非常簡單包括PowerShell和C#。請參閱https://ss64.com/ps/syntax-env.html。 –

回答

1

謝謝大家你的幫助,你把我放在正確的軌道上。這裏是最後的工作代碼

var nodePath = HttpContext.Server.MapPath("~/.bin/node.exe"); 
var mjmlFromStringCmd = HttpContext.Server.MapPath("~/.bin/mjmlFromString"); 
var mjmlTemplate = System.IO.File.ReadAllText(HttpContext.Server.MapPath("~/.bin/test.mjml")); 
var command = $"$htmlOutput = {nodePath} {mjmlFromStringCmd} -c '{mjmlTemplate}'"; 

var powerShell = PowerShell.Create(); 

powerShell.AddScript(command); 
powerShell.Invoke(); 
// GetVariable returns an "object", that is in fact an array of PSObjec 
var lines = ((object[]) powerShell.Runspace.SessionStateProxy.GetVariable("htmlOutput")).Cast<PSObject>(); 
// Agregate all returned PSObjec (each one of them being a line from the powershell output) and aggregate them into a string 
output = t.Aggregate(output, (current, item) => current + item.BaseObject.ToString()); 

花了大量的扭曲,但它確實有效。

1

我從來沒有這樣做過,但好像你不是誰都有這個問題只有一個,檢查出答案了在:

How to get value from powershell script into C# variable?

passing powershell variables to C# code within PS script

+0

當使用[this](https://stackoverflow.com/a/44477456/6838730)方法時,我得到一個ps.Invoke()返回一個空列表。另一個只是不會工作(我試圖調試它) – Wndrr

+0

所以我試了兩個,我得到一個列表包含0結果在這兩種情況下: -/ – Wndrr

+0

所以我沒有在C#的經驗,我不能真正與您一起測試,但在該代碼中設置了執行策略。這需要管理權限。 也許以管理員身份運行你的代碼?它是一個長鏡頭 – Snak3d0c