无法加载System.Management.Automation 7.1.0.0的DSC命令执行错误
问题触发场景
执行DSC应用命令:Start-DSCConfiguration -ComputerName localhost -Path ./CsharpExample -Verbose -Wait -Force
时触发报错:
InvalidOperation: Importing module cSharpDSCResource failed with error - Could not load file or assembly 'System.Management.Automation, Version=7.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
已确认的环境信息
- 自定义资源DLL存储路径:
"C:\Program Files\WindowsPowerShell\Modules\cSharpDSCResource\DSCResources\cSharpDSCResource\cSharpDSCResource.dll" - 程序集加载校验结果:
- 在PowerShell 5 版本提示符下,执行
[appdomain]::CurrentDomain.GetAssemblies() | Sort-Object -Property FullName | Select-Object -Property FullName,仅加载System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35版本程序集 - 在PowerShell 7 版本提示符下,同命令可正常加载
System.Management.Automation, Version=7.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35版本程序集
- 在PowerShell 5 版本提示符下,执行
- 资源识别状态:执行
Get-DSCResource可正常枚举到cSharpDSCResource,返回结果为:Binary cSharpDSCResource cSharpDSCResource 0.0.1 {Path, Content, DependsOn, Ensure...} - 开发环境包含Windows管理框架、Microsoft .NET SDK 5.0.101,项目配置文件cSharpDSCresource.csproj原始内容:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net5.0</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="System.Management.Automation" Version="7.1.0" /> </ItemGroup> </Project>
问题根因
Windows内置的传统DSC执行引擎是强绑定Windows PowerShell 5.1运行时的,执行配置时的模块加载流程完全运行在5.1的AppDomain上下文里,根本不会识别、加载PowerShell 7上下文专属的程序集。
当前编译的cSharpDSCResource直接绑定了System.Management.Automation 7.1.0.0版本的依赖,当5.1宿主加载这个DLL时,会严格按照编译时记录的版本号匹配依赖项,因为宿主上下文里不存在对应版本的程序集,就会抛出文件找不到的错误——哪怕把7.1.0版本的DLL放在资源同目录下,.NET运行时也会因为版本校验规则、上下文隔离机制无法完成绑定。
可落地修复步骤
- 适配传统DSC引擎的运行环境:
- 修改csproj的TargetFramework,将
net5.0改为net472,匹配Windows PowerShell 5.1对应的.NET Framework运行时版本 - 移除项目中直接引用的
System.Management.Automation 7.1.0NuGet包,改为引用适配.NET Framework的PS兼容版本(对应4.3.0版本,和5.1宿主自带的程序集版本完全匹配) - 重新编译DLL,替换模块目录下原有的cSharpDSCResource.dll后重新执行DSC命令
- 修改csproj的TargetFramework,将
- 如需保留PS7的运行时能力,需切换到PowerShell 7原生支持的DSC执行链路,不能继续使用Windows PowerShell 5.1入口的
Start-DSCConfiguration命令 - 快速验证定位:在PowerShell 5的提示符下手动执行
Import-Module "C:\Program Files\WindowsPowerShell\Modules\cSharpDSCResource\DSCResources\cSharpDSCResource\cSharpDSCResource.dll" -Verbose,可复现完全一致的程序集加载错误,确认问题为版本绑定不匹配
内容的提问来源于stack exchange,提问作者scranley

