2013-11-28 34 views
1

我正在執行使用C#的PowerShell腳本,但是當我嘗試在PowerShell腳本中獲取環境變量時,它不起作用。

如果我使用控制檯手動運行powershell腳本,它將起作用。

你對如何解決這個問題有什麼想法嗎?對於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(); 

腳本的PowerShell:

$path = $env:PATH; 
write-output $path # this is empty ! $env does seems to exist in the runspace ? 
+0

我通過使用腳本[here](http://stackoverflow.com/a/14382047/1832488)找到了解決方法,但我更願意找到如何配置運行空間,以便設置Env變量。 – codea

回答

0

改變這一行:

Command command = new Command(script, false); 

Command command = new Command(script, true); 

script變量是一個腳本(多個命令)。通過傳遞false,PowerShell認爲script命名命令。

+0

我傳遞一個.ps1文件路徑作爲命令,如果我使用(script,true)它不起作用。 – codea

+0

爲了使它工作,我首先將該文件作爲字符串讀取,然後使用Command command = new Command(script,true); – codea

0

也許你可以嘗試,而不是你PowerShell腳本的代碼。不管劇本如何調用這應該工作:

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

在這樣的環境變量操作更多信息,可以發現here

+0

我試過了,但它不起作用。謝謝(你的)信息。 – codea

0

唯一值得關注的是在創建運行空間時沒有傳入配置。

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

我主持PowerShell未編寫單元測試PowerShell的插件做的唯一的事情。代碼在這裏:https://github.com/openxtra/TimeTag/tree/master/Test

查看用於測試項目的DatabasePoSHSnapInTest和PowerStatsPoSHSnapInTest文件夾。

+0

當我創建一個新配置並將其傳遞給我的運行空間時,它們都不起作用。 – codea