调用pwsh触发"Assembly with same name is already loaded"错误的原因与解决办法
问题描述
我有一个基于Windows PowerShell 5运行的脚本,目前无法迁移到PowerShell Core(v7+)。该脚本会调用一些子脚本,我希望在部分子脚本中使用PowerShell 7+的特性。最初采用以下方式调用子脚本:
pwsh -WorkingDirectory . -File .\Configure.ps1
但Configure.ps1在导入模块时报错:
Import-Module: path\to\script\Configure.ps1:3 Line | 3 | Import-Module CustomModule | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Assembly with same name is already loaded
CustomModule依赖IISAdministration模块。经测试,在PowerShell 7.3.3会话中直接执行相同代码也会触发该错误,与旧版PowerShell无关;但直接运行.\Configure.ps1则完全正常。
错误原因
核心是程序集加载冲突,具体细节:
- 用
pwsh -File启动脚本时,PowerShell 7的宿主进程会提前加载部分系统程序集,其中包含IISAdministration依赖的基础程序集。 CustomModule可能打包了同名但版本不同的程序集,或者其加载逻辑未处理版本兼容问题,导致导入时发现同名程序集已被加载,触发冲突。- 直接运行脚本时,脚本在PowerShell 5会话中执行,其程序集加载机制与PowerShell 7不同,且不会提前加载引发冲突的程序集,因此无报错。
解决方法
- 调整模块导入逻辑:在
CustomModule的.psd1文件中,通过RequiredAssemblies指定依赖程序集的明确版本;或者在.psm1中用[System.Reflection.Assembly]::Load()指定版本号,避免加载冲突版本。 - 启用无配置文件会话:调用子脚本时添加
-NoProfile参数,避免PowerShell 7加载配置文件中提前导入的模块/程序集:pwsh -NoProfile -WorkingDirectory . -File .\Configure.ps1 - 统一模块版本:检查PowerShell 7中
IISAdministration模块的版本,确保与CustomModule依赖的版本一致。查看版本命令:
若版本不匹配,安装对应版本:Get-Module -ListAvailable IISAdministrationInstall-Module -Name IISAdministration -RequiredVersion x.x.x -Force - 添加程序集绑定重定向:在
Configure.ps1开头插入绑定重定向配置,强制加载指定版本的冲突程序集。示例代码:$bindingRedirect = @" <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="冲突程序集名称" publicKeyToken="对应公钥令牌" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-冲突版本号" newVersion="目标版本号" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration> "@ $tempConfig = [IO.Path]::GetTempFileName() [System.IO.File]::WriteAllText($tempConfig, $bindingRedirect) [System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $tempConfig)
内容的提问来源于stack exchange,提问作者Matt H
相关产品推荐
相关产品推荐

