2014-04-24 19 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)和所以放弃了这种做法 –

相关问题