You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8无法导入ActiveDirectory模块,但PowerShell可正常使用

.NET 8中加载PowerShell ActiveDirectory模块时找不到程序集的问题

问题详情

  • 在.NET 8控制台应用中尝试初始化PowerShell运行空间并导入ActiveDirectory模块时,抛出错误:
    无法加载文件或程序集'Microsoft.ActiveDirectory.Management, Culture=neutral, PublicKeyToken=null',系统找不到指定文件。
  • 已完成的配置操作:
    • 项目安装了Microsoft.PowerShell.SDK NuGet包,未直接引用System.Management.Automation包
    • 通过Windows 11「添加功能」安装了PowerShell ActiveDirectory模块,且所有RSAT相关包已安装
    • 本地C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ActiveDirectory路径下存在完整模块文件,WinSys文件夹中也有对应的.dll
    • PowerShell终端中可正常使用ActiveDirectory模块,但.NET应用无法识别该模块
    • 相同代码在同事的电脑上可正常运行

测试代码

using System.Management.Automation.Runspaces;
// ...
var initial = InitialSessionState.CreateDefault();
initial.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;

initial.ImportPSModule(["ActiveDirectory"]);
using var runspace = RunspaceFactory.CreateRunspace(initial);

try
{
    runspace.Open();
}
catch(Exception ex)
{
    Console.WriteLine(ex.ToString());
}

临时解决方法

将C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ActiveDirectory下的模块文件及.dll复制到自定义文件夹,修改代码从该自定义路径导入模块,问题得以解决。

遗留疑问

系统已正确安装ActiveDirectory模块且PowerShell可正常识别,但.NET应用无法自动找到该模块的具体原因是什么?

内容的提问来源于stack exchange,提问作者chuftica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 07:03:17