c# - 为什么在 c# 中通过启动进程运行 powershell 时不导入 powershell 模块?

标签 c# windows powershell

我有一个 c# 应用程序,它使用以下代码来调用 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

脚本失败:

脚本执行期间发生错误:Import-Module:未加载指定的模块“Servermanager”,因为在任何模块目录中都找不到有效的模块文件。

当我在机器上的 powershell 中运行脚本时,这工作正常。

在机器上执行 Get-Module : Format-List 结果:

名称:服务器管理器 路径:C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Servermanager\ServerManager.psm1 描述 : 模块类型:脚本 版本:2.0.0.0 嵌套模块:{Microsoft.Windows.ServerManager.PowerShell} ExportedFunctions:{禁用-ServerManagerStandardUserRemoting,启用-ServerManagerStandardUserRemoting} ExportedCmdlets:{Get-WindowsFeature、安装-WindowsFeature、卸载-WindowsFeature} 导出变量: 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 平台安装程序\; 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

我还检查了脚本在从应用程序调用时与直接从 PS 运行时是否以同一用户使用相同版本的 powershell 运行。

是什么阻止了 PS 加载 ServerManager 模块?

最佳答案

原来和平台目标有关。构建为 AnyCPU(选中“首选 32 位”复选框)或构建为 x86,我们看到了这个问题。构建为 x64,问题在我正在安装的 64 位 Windows 上消失了。

关于c# - 为什么在 c# 中通过启动进程运行 powershell 时不导入 powershell 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23269447/

相关文章:

c# - ListBox - 值被设置为文本字段

c# - 子表单从多个父表单获取属性

c# - 将对象深拷​​贝到 List 中

用于 winRT 的 Python 投影(绑定(bind))?

.net - 从Powershell运行MSBuild而不指定.Net版本

c# - 让用户选择要在 WPF DataGrid 上显示的列

c++ - Windows proc/callback 函数可以是类的成员函数吗?

c# - PowerShell 和 C# 在枚举集合时的区别

PowerShell 删除最后一个错误

windows - 新电脑,git pull origin 要求输入密码