TIK*_*KSN 5 c# powershell json .net-assembly
我正在开发PowerShell 二进制模块。它使用Json.NET和其他库。
我收到此异常“无法加载文件或程序集 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' 或其依赖项之一。系统找不到指定的文件。”
在硬盘上,我有一个更新版本(版本 7.0.2)
像这样的问题在控制台、网络或桌面应用程序中很容易解决,通过这样的行使用app.config或“web.config”
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
Run Code Online (Sandbox Code Playgroud)
如何为 PowerShell 二进制模块做类似的事情?
在开发使用多个 3rd 方库(Google API、Dropbox、Graph 等)的 PowerShell 模块时,我自己遇到了这个问题,我发现以下解决方案是最简单的:
public static Assembly CurrentDomain_BindingRedirect(object sender, ResolveEventArgs args)
{
var name = new AssemblyName(args.Name);
switch (name.Name)
{
case "Microsoft.Graph.Core":
return typeof(Microsoft.Graph.IBaseClient).Assembly;
case "Newtonsoft.Json":
return typeof(Newtonsoft.Json.JsonSerializer).Assembly;
case "System.Net.Http.Primitives":
return Assembly.LoadFrom("System.Net.Http.Primitives.dll");
default:
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,在方法中,我有两种可能的方法来引用程序集,但是它们都做同样的事情,它们强制使用该程序集的当前版本。(无论是通过类引用加载还是dll文件加载)
要在任何 cmd-let 中使用它,请在 PSCmdLet 的 BeginProcessing() 方法中添加以下事件处理程序。
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_BindingRedirect;
Run Code Online (Sandbox Code Playgroud)
您需要将清单添加到您的模块中。
最简单的方法是:
New-ModuleManifest -RequiredAssemblies:"path\to\newtonSoft.dll"
Run Code Online (Sandbox Code Playgroud)
然后手动修改清单文件以进行任何其他调整。
如果清单不能解决问题,您可能需要拿出核锤并为所有 powershell 设置绑定重定向,如Powershell - 应用程序配置文件中未找到程序集绑定重定向中所述