PowerShell脚本加载.NET Core DLL遇到问题求助
解决PowerShell加载依赖Azure存储的.NET Core 8 DLL时的ReflectionTypeLoadException问题
你在PowerShell中加载依赖Azure.Storage和Azure.Storage.Blobs的.NET Core 8类库TestClassLibrary.dll时触发ReflectionTypeLoadException,尝试手动下载依赖DLL、执行dotnet add package均未解决,以下是针对性的解决思路:
1. 确保所有依赖DLL与主DLL在同一目录
Add-Type加载DLL时,.NET运行时会优先在主DLL所在目录查找依赖项。如果Azure.Storage.dll、Azure.Storage.Blobs.dll及其依赖的Azure.Core.dll等文件不在该目录,会导致加载失败。
- 操作步骤:
- 从NuGet获取对应版本的
Azure.Storage.Blobs包,提取lib/net8.0目录下的所有DLL - 将这些依赖DLL下载到
$env:TEMP目录(与TestClassLibrary.dll同路径) - 按依赖顺序加载所有DLL,再加载主DLL:
# 先加载基础依赖 Add-Type -Path "$env:TEMP\Azure.Core.dll" Add-Type -Path "$env:TEMP\Azure.Storage.dll" Add-Type -Path "$env:TEMP\Azure.Storage.Blobs.dll" # 最后加载业务类库 Add-Type -Path $testClassPath -PassThru
- 从NuGet获取对应版本的
2. 验证PowerShell运行时兼容性
- Windows PowerShell 5.x基于.NET Framework,无法直接加载.NET Core/.NET 5+的类库,必须使用PowerShell 7+(基于.NET 5+)
- 验证命令:
# 确认是Core版本PowerShell $PSVersionTable.PSEdition # 确认运行时版本≥8.0 $PSVersionTable.RuntimeVersion
3. 生成包含所有依赖的独立部署包
若你有权限重新编译TestClassLibrary,可通过dotnet publish生成包含所有依赖的独立包,避免手动收集DLL:
dotnet publish -c Release -f net8.0 -r win-x64 --self-contained true
将发布目录下的所有文件上传到下载服务器,PowerShell中下载整个目录后直接加载主DLL即可。
4. 精准定位缺失的依赖
你的代码已捕获LoaderExceptions,但输出不够详细,修改代码打印每个异常的具体信息:
catch [System.Reflection.ReflectionTypeLoadException] { Write-Host "ReflectionTypeLoadException 详情:" foreach ($ex in $_.Exception.LoaderExceptions) { Write-Host "------------------------" Write-Host "异常信息: $($ex.Message)" Write-Host "缺失程序集: $($ex.FileName)" } }
根据输出的缺失程序集名称,针对性补充对应DLL即可。
5. 放弃使用dotnet add package解决问题
dotnet add package是.NET项目的包管理命令,需要在存在.csproj文件的目录下执行,直接在PowerShell中运行不会将依赖DLL放到主DLL的加载路径中,无法解决当前问题。
原始问题代码
param( [string]$Name ) #Download the DLL $testClassPath = "$env:TEMP\TestClassLibrary.dll"; $assemblyUrlPath = "https://some.url/TestClassLibrary.dll"; try { $webClient = New-Object System.Net.WebClient; $webClient.DownloadFile($assemblyUrlPath, $testClassPath); $webClient.Dispose(); } catch [System.Exception] { } if (Test-Path $testClassPath) { Write-Output "Dlls exists." #install package? #dotnet add package Azure.Storage.Blobs; #Try to Create an instance of the class from the DLL try { Add-Type -Path $testClassPath -PassThru # Create an instance of TestProcessFile with the fileName argument $testProcessFile = New-Object TestClassLibrary.TestProcessFile $Name # Call the async method ProcessAsync and wait for it to complete $task = $testProcessFile.ProcessAsync() $task.Wait() } catch [System.Reflection.ReflectionTypeLoadException] { Write-Host "Message: $($_.Exception.Message)" Write-Host "StackTrace: $($_.Exception.StackTrace)" Write-Host "LoaderExceptions: $($_.Exception.LoaderExceptions)" } } else { Write-Output "File does not exist." }
内容的提问来源于stack exchange,提问作者David Alejandro García García
相关产品推荐
相关产品推荐

