1

I am executing a powershell script using C#, but when I try to get an environment variable inside the powershell script it does not work.

If I run the powershell script manually using the console it works.

Do you have any idea on how to solve this issue ?

Code sample for C#:

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

// set directory for ps
if (!string.IsNullOrEmpty(sessionPath))
    runspace.SessionStateProxy.Path.SetLocation(sessionPath);

Pipeline pipeline = runspace.CreatePipeline();
Command command = new Command(script, false);
pipeline.Commands.Add(command);
pipeline.Commands.Add("Out-String");
pipeline.InvokeAsync();

script powershell:

$path = $env:PATH;
write-output $path # this is empty ! $env does seems to exist in the runspace ? 
abatishchev
  • 98,240
  • 88
  • 296
  • 433
codea
  • 1,439
  • 1
  • 17
  • 31
  • I found a workaround by using the script [here](http://stackoverflow.com/a/14382047/1832488) but I would prefer to find how to configure the runspace so the Env variable is set. – codea Nov 28 '13 at 17:26

3 Answers3

0

Maybe you could try this code instead in your PowerShell script. This should work regardless of how the script is invoked:

$path = [environment]::GetEnvironmentVariable("Path")
write-output $path

More info on environment variable manipulation of this kind can be found here.

Baldrick
  • 11,712
  • 2
  • 31
  • 35
0

The only thing that springs to mind is that you are not passing in a configuration when creating the run space.

var config = RunspaceConfiguration.Create();
var runspace = RunspaceFactory.CreateRunspace(config);

The only thing I've done hosting Powershell was writing unit tests for a Powershell plugin. Code is here: https://github.com/openxtra/TimeTag/tree/master/Test

See DatabasePoSHSnapInTest and PowerStatsPoSHSnapInTest folders for the test projects.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
Jack Hughes
  • 5,514
  • 4
  • 27
  • 32
0

Change this line:

Command command = new Command(script, false);

to

Command command = new Command(script, true);

Your script variable is a script (multiple commands). By passing false, PowerShell thinks that script names a command.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • I am passing a .ps1 file path as a command, if I use (script,true) it does not work. – codea Dec 11 '13 at 11:44
  • To make it work, I read the file as string first, then I used Command command = new Command(script, true); – codea Dec 11 '13 at 11:53