从C#中的powershell获取var

时间:2017-09-26 12:37:48

标签: c# powershell

我在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变量的值?

2 个答案:

答案 0 :(得分:1)

我以前从未这样做,但似乎你不是唯一有这个问题的人,请查看以下答案:

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

passing powershell variables to C# code within PS script

答案 1 :(得分: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()); 

经历了很多大脑扭曲,但确实有效。