[英]Why do powershell modules not import when running powershell via start process in c#?
我有一個ac#application,它使用以下代碼來shellhell對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-Module:Format-List會導致:
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
帶外殼腳本中的$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模塊?
事實證明它與平台目標有關。 構建為AnyCPU(選中'prefer 32bit'復選框)或構建為x86,我們看到了這個問題。 構建為x64,問題在我正在安裝的64位窗口上消失。
你可以嘗試這樣的事情:
Collection<PSObject> psResult = PowerShell.Create().AddScript(YourScriptString).Invoke()
PSObject
類允許獲取腳本返回的對象的任何屬性值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.