Monday, March 21, 2011

Loading the functions from a powershell script into session memory

.
The answer is ".".
Used like this:
. .\ApowershellScript.ps1
And then within the same powershell session I could do this:
SomeFunctionFromTheAforementionedScript ARandomArgument
And it would work.

I had been calling Process.Start, but the call started failing once I tried adding the call to the powershell function within it.
So this did not work:
1 ProcessStartInfo info = new ProcessStartInfo("powershell.exe");
2 info.Arguments = "{ . C:\\LivingRoom\\ir.ps1; sendIR " + command + " }";
3 info.RedirectStandardError = true;
4 info.RedirectStandardOutput = true;
5
6 info.UseShellExecute = false;
7
8 System.Diagnostics.Process process = Process.Start(info);

So this is what I did get to work:

1 Runspace rs = RunspaceFactory.CreateRunspace();
2 rs.Open();
3
4 Pipeline pipeline = rs.CreatePipeline();
5 Command command3 = new Command(" . C:\\LivingRoom\\ir.ps1", true, false);
6 Command command4 = new Command(" sendir " + command, true);
7 pipeline.Commands.Add(command3);
8 pipeline.Commands.Add(command4);
9 pipeline.Invoke();

It's all about the .

In order to use a Runspace in C#, I had to know the super-secret location of the .net assembly that contained the Runspace code.
C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll
The fact that they hid it is this odd location is weird. :P
Oh well.

No comments:

Post a Comment