PowerShell脚本导入Exchange程序集遇System.Runtime等依赖加载错误求助
解决PowerShell加载.NET 8编译的DLL时的System.Runtime/System.ServiceModel.Primitives依赖问题
问题根源
你的C# DLL是基于**.NET 8**编译的,但PowerShell运行环境(比如Windows PowerShell基于.NET Framework,或PowerShell 7+未安装.NET 8 Runtime)无法找到.NET 8专属的依赖组件,导致加载失败。
解决方案
1. 匹配PowerShell与C#项目的.NET环境
- 先确认PowerShell的运行环境:
# 查看PowerShell版本和.NET运行时信息 $PSVersionTable- 如果是Windows PowerShell 5.x:它基于.NET Framework,不支持.NET 8依赖。需将C#项目的目标框架改为
.NET Framework 4.7.2+或.NET Standard 2.0,同时更新Exchange相关NuGet包到对应框架的兼容版本,重新编译DLL。 - 如果是PowerShell 7+:确保已安装.NET 8桌面运行时或ASP.NET Core运行时,安装后重启PowerShell再尝试加载DLL。
- 如果是Windows PowerShell 5.x:它基于.NET Framework,不支持.NET 8依赖。需将C#项目的目标框架改为
2. 手动复制所有依赖DLL到脚本目录
找到C#项目编译输出文件夹(通常是bin/Release/net8.0)中的所有依赖文件,包括:
System.Runtime.dll(版本8.0.0.0)System.ServiceModel.Primitives.dll(版本8.0.0.0)- 其他关联的.NET 8类库DLL
将这些文件和你的Reference.dll放在同一目录下,然后批量加载:
Get-ChildItem -Path ".\*.dll" | ForEach-Object { Add-Type -Path $_.FullName }
3. 使用绑定重定向(仅适用于.NET Framework环境)
如果坚持用Windows PowerShell(.NET Framework),可通过绑定重定向让系统用已有的高版本兼容组件替代.NET 8的依赖:
- 在脚本同目录下创建
powershell.exe.config文件,内容如下:
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="4.3.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.ServiceModel.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <!-- 替换为你已安装的System.ServiceModel.Primitives版本号 --> <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="4.xx.x.x" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
- 重启PowerShell后重新执行脚本。
4. 替代方案:直接用PowerShell Exchange模块
如果只是获取Outlook日历,可跳过自定义DLL,直接使用官方Exchange Online PowerShell模块:
# 安装模块(首次运行) Install-Module -Name ExchangeOnlineManagement -Force # 连接Exchange Online Connect-ExchangeOnline # 获取日历事件 Get-CalendarEvents -Mailbox "your-email@domain.com" -StartDate (Get-Date) -EndDate (Get-Date).AddDays(7)
经验提示
- 优先保证C#项目的目标框架与PowerShell运行的.NET环境一致,从根源避免跨版本依赖冲突。
- 编译C#项目时,选择“自包含部署”模式(如果适用),可将所有依赖打包到输出目录,减少外部依赖缺失问题。
内容的提问来源于stack exchange,提问作者kylian35
相关产品推荐
相关产品推荐

