Windows 2008 R2下PowerShell模块System.Net.Http加载失败求助
解决方案:PowerShell模块下System.Net.Http绑定重定向失效问题(.NET 4.5.2/Windows 2008 R2)
方法1:创建PowerShell模块专属配置文件
PowerShell模块的配置文件需与模块DLL同名(格式为[模块DLL名称].config),且放置在同一目录下。将GUI模块中生效的绑定重定向配置复制到该文件:
<?xml version="1.0" encoding="utf-8"?> <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/> <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="4.0.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
若模块通过.psm1脚本加载DLL,确保配置文件与DLL路径一致,PowerShell会自动读取该配置。
方法2:在PowerShell脚本中手动注入绑定重定向
在模块的.psm1初始化脚本开头添加以下代码,强制当前AppDomain加载指定重定向规则:
$redirectConfig = @" <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/> <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="4.0.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> </configuration> "@ # 生成临时配置文件 $tempConfigPath = [System.IO.Path]::GetTempFileName() + ".config" Set-Content -Path $tempConfigPath -Value $redirectConfig -Encoding utf8 # 让当前AppDomain加载该配置 $domain = [System.AppDomain]::CurrentDomain $domain.SetData("APP_CONFIG_FILE", $tempConfigPath) # 模块加载完成后可清理临时文件 # Remove-Item -Path $tempConfigPath -Force
方法3:确保System.Net.Http文件复制到模块输出目录
检查PowerShell模块项目的引用设置:
- 找到
System.Net.Http引用,将Copy Local属性设为True - 若使用NuGet包安装,确认
System.Net.Http相关文件(如System.Net.Http.dll)被复制到模块输出目录 - 删除项目中旧版本的
System.Net.Http引用,避免版本冲突
方法4:通过程序集加载事件手动拦截重定向
在模块初始化代码中注册程序集加载事件,当请求加载指定版本的System.Net.Http时,手动返回4.0.0.0版本:
[System.AppDomain]::CurrentDomain.add_AssemblyResolve({ param($sender, $args) $assemblyName = New-Object System.Reflection.AssemblyName($args.Name) if ($assemblyName.Name -eq "System.Net.Http" -and $assemblyName.Version -ne [Version]"4.0.0.0") { $localDllPath = Join-Path $PSScriptRoot "System.Net.Http.dll" if (Test-Path $localDllPath) { return [System.Reflection.Assembly]::LoadFrom($localDllPath) } } return $null })
内容的提问来源于stack exchange,提问作者Le ZVince
相关产品推荐
相关产品推荐

