2014-04-24 35 views
3

我有一個使用下面的代碼來調用掏出一個PowerShell腳本C#應用程序:爲什麼在c#中通過啓動進程運行powershell時不能導入powershell模塊?

string scriptFileToExecute = "someScript.ps1; 
var startInfo = new ProcessStartInfo(); 
startInfo.FileName = @"powershell.exe"; 
startInfo.RedirectStandardOutput = true; 
startInfo.RedirectStandardError = true; 
startInfo.UseShellExecute = false; 
startInfo.CreateNoWindow = false; 
startInfo.Arguments = string.Format(@"& '{0}' '{1}'", scriptFileToExecute, "argument"); 

var process = new Process { StartInfo = startInfo }; 
process.Start(); 

string output = process.StandardOutput.ReadToEnd(); 

該工程確定並運行該腳本。

然而,當我加入這一行的腳本:

Import-Module ServerManager 

腳本失敗:

errors occurred during script execution: Import-Module : The specified module 'Servermanager' was not loaded because no valid module file was found in any module directory.

時,我只是在機器上運行的PowerShell腳本這工作得很好。

做一個GET-模塊:格式列表機器結果:

Name : Servermanager Path : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Servermanager\ServerManager.psm1 Description : ModuleType : Script Version : 2.0.0.0 NestedModules : {Microsoft.Windows.ServerManager.PowerShell} ExportedFunctions : {Disable-ServerManagerStandardUserRemoting, Enable-ServerManagerStandardUserRemoting} ExportedCmdlets : {Get-WindowsFeature, Install-WindowsFeature, Uninstall-WindowsFeature} ExportedVariables : ExportedAliases : {Add-WindowsFeature, Remove-WindowsFeature}

,幷包括在掏了腳本結果$env:path在:

C:\Windows\system32; C:\Windows;C:\Windows\System32\Wbem; C:\Windows\System32\WindowsPowerShell\v1.0\; C:\Program Files\Microsoft\Web Platform Installer\; C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\; C:\Program Files\Microsoft SQL Server\110\Tools\Binn\

$env:PSModulePath輸出:

C:\Users\Administrator.PORTAL\Documents\WindowsPowerShell\Modules; C:\Program Files (x86)\WindowsPowerShell\Modules; C:\Windows\system32\WindowsPowerShell\v1.0\Modules\

這似乎意味着,它應該加載模塊,因爲它存在於C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Servermanager\ServerManager.psm1

我也檢查了從應用程序調用爲腳本時,與相同版本的PowerShell的相同用戶運行當直接從PS運行時。

什麼可能阻止PS加載ServerManager模塊?

回答

2

所以它證明與平臺目標有關。構建爲AnyCPU(選中'prefer 32bit'複選框)或構建爲x86,並且我們看到此問題。構建爲x64,問題在我安裝的64位Windows上消失。

0

能否請您嘗試這樣的事:

Collection<PSObject> psResult = PowerShell.Create().AddScript(YourScriptString).Invoke() 

PSObject類允許獲得由腳本返回的對象的任何屬性值。

+1

不幸的是,這需要應用程序作爲PSHost或用戶交互位不起作用(例如'Write-Host'產生一個錯誤)。最初這是我如何使應用程序工作,但得到類似於[這個問題]的錯誤(http://stackoverflow.com/questions/12930762/how-to-pass-arguments-to-powershell-via-c-sharp)和所以放棄了這種做法 –

相關問題