C#调用PowerShell SDK在Windows Server 2019加载ServerManager模块失败
C#调用PowerShell加载ServerManager模块失败解决方法
错误对应原因
- 报错
The 'Get-WindowsFeature' command was found in the module 'ServerManager', but the module could not be loaded:进程运行在32位环境,无法加载64位系统目录下的ServerManager模块 - 报错
The term 'Get-WindowsFeature' is not recognized:使用了.NET Core/.NET 5+版本的PowerShell SDK,或模块搜索路径未包含ServerManager的存放目录
必做配置
- 强制项目运行在64位平台
ServerManager模块仅内置在64位版本的Windows PowerShell 5.1中,32位进程的模块搜索路径不会包含64位系统模块目录。打开项目属性的生成设置,将目标平台从Any CPU或x86修改为x64即可解决架构不匹配问题。 - 适配对应PowerShell SDK
.NET Core/.NET 5+对应的PowerShell 7+ SDK默认不会加载Windows原生PowerShell 5.1的专属模块,需将项目切换为.NET Framework 4.5+版本,安装NuGet包PowerShellStandard.Library即可适配系统原生PowerShell环境。
可选兜底配置
如果完成上述配置后仍无法加载模块,可直接指定ServerManager模块的完整路径导入,跳过模块搜索步骤:
InitialSessionState initialSessionState = InitialSessionState.CreateDefault(); // 直接指定模块完整路径导入 initialSessionState.ImportPSModule(new string[] { @"C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ServerManager\ServerManager.psd1" }); Runspace powerShellRunscape = RunspaceFactory.CreateRunspace(initialSessionState); powerShellRunscape.Open(); using PowerShell powerShell = PowerShell.Create(); powerShell.Runspace = powerShellRunscape; powerShell.AddCommand("Get-WindowsFeature"); powerShell.AddArgument(featureName); var result = powerShell.Invoke();
验证结论
.NET Framework版本的项目完成64位运行配置后,即可正常调用Get-WindowsFeature命令完成Windows组件检测。
内容的提问来源于stack exchange,提问作者user1085907
相关产品推荐
相关产品推荐

