Mathieu VIALES
Mathieu VIALES

Reputation: 4772

Get var from powershell in C#

I run a command in Powershell from C#, and I need to read the content of a var. I tried all the solutions I found online but none worked so far.

Here is my current code (with some "attempts" still included)

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;

and here is the executed powershell command

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

If I run the command directly in a powershell prompt, the $htmlOutput var gets its value and I can print it by calling

$htmlOutput

Is there some trick with the C# powershell class that I missed ? How can I get the value of the powershell htmlOutput variable in C# ?

Upvotes: 1

Views: 4144

Answers (2)

Mathieu VIALES
Mathieu VIALES

Reputation: 4772

Thank you all for your help, you put me on the right tracks. Here is the final working code

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()); 

Took a lot of brain-twisting but it does work.

Upvotes: 3

Snak3d0c
Snak3d0c

Reputation: 626

I've never done this before but seems like you are not the only one who has this question, check out the answers over at :

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

passing powershell variables to C# code within PS script

Upvotes: 1

Related Questions