.NET 6应用执行含Active Directory模块的PowerShell脚本失败
问题背景
在IIS托管的.NET 6应用里,执行简单PowerShell脚本(比如Write-Host "Hello World")完全正常,但一添加AD相关代码(例如Get-ADUser -Filter "Name -eq 'admin'"),就会抛出看似无关的WCF配置错误:
System.TypeInitializationException: The type initializer for 'System.ServiceModel.Diagnostics.TraceUtility' threw an exception.\r\n ---> System.Configuration.ConfigurationErrorsException: The 'system.serviceModel/diagnostics' configuration section cannot be created. The machine.config file is missing information. Verify that this configuration section is properly registered and that you have correctly spelled the section name. For Windows Communication Foundation sections, run ServiceModelReg.exe -i to fix this error.
已知条件:执行用户权限正常,AD模块可用,未修改过machine.config。
解决思路
补全.NET 6的WCF依赖包
.NET 6及后续版本默认不包含完整WCF组件,但AD PowerShell模块依赖WCF与AD Web服务通信。给应用安装兼容的WCF NuGet包:System.ServiceModel.Diagnostic和System.ServiceModel.Primitives。手动添加WCF诊断节配置
即便系统machine.config没问题,IIS托管应用可能无法读取系统级配置。直接在应用的web.config里手动注册并添加诊断节:<configuration> <configSections> <sectionGroup name="system.serviceModel"> <section name="diagnostics" type="System.ServiceModel.Configuration.DiagnosticSection, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </sectionGroup> </configSections> <system.serviceModel> <diagnostics /> </system.serviceModel> </configuration>调整应用程序池设置
若应用程序池设为.NET CLR版本: 无托管代码(符合.NET 6无托管特性),可能导致加载WCF配置异常。试试临时将CLR版本改为v4.0测试,同时确认启用32位应用程序选项设为False(AD模块通常为64位)。换用直接调用AD的.NET库
绕开PowerShell脚本,直接在.NET 6代码中使用System.DirectoryServices.AccountManagement库查询AD,避免依赖PowerShell的WCF调用逻辑:using System.DirectoryServices.AccountManagement; using (var domainContext = new PrincipalContext(ContextType.Domain)) { var targetUser = UserPrincipal.FindByIdentity(domainContext, "admin"); // 后续处理用户数据 }重新注册系统WCF组件
虽然未修改过machine.config,但可尝试修复WCF配置注册。以管理员身份打开命令提示符,进入对应.NET框架目录(比如C:\Windows\Microsoft.NET\Framework64\v4.0.30319),执行:ServiceModelReg.exe -i
内容的提问来源于stack exchange,提问作者Kamil

